我希望获取 XML 文件中特定节点下的元素计数。
该文件将如下所示
<Return>
<ReturnHeader>
</ReturnHeader>
<ReturnData documentCnt="8">
<file1></file1>
<file2></file2>
<file3></file3>
<file4></file4>
<file5></file5>
<file6></file6>
<file7></file7>
<file8></file8>
</ReturnData>
<ParentReturn>
<ReturnHeader>
</ReturnHeader>
<ReturnData documentCnt="6">
<file1></file1>
<file2></file2>
<file3></file3>
<file4></file4>
<file5></file5>
<file6></file6>
</ReturnData>
</ParentReturn>
<SubsidiaryReturn>
<ReturnHeader>
</ReturnHeader>
<ReturnData documentCnt="3">
<file1></file1>
<file2></file2>
<file3></file3>
</ReturnData>
</SubsidiaryReturn>
</Return>
我需要解析此 xml 文件中的 ReturnData 节点(如您所见,该节点位于文件中的多个位置)并获取其下方元素的计数。
例如
- 在 Return\ReturnData 下,计数必须为 8
- 在 Return\ParentReturn\ReturnData 下,计数必须为 6
- 在 Return\SubsidiaryReturn\ReturnData 下,计数必须为 3
属性 documentCnt 实际上应该给我正确的计数,但创建的 xml 文档会有差异,因此我需要解析此 xml 文件并检查 documentCnt 属性中的值是否与 ReturnData 节点下的元素数量匹配。
使用您给出的问题描述:
属性 documentCnt 实际上应该给我正确的计数,但是
创建的 xml 文档会有差异,因此我
需要解析这个 xml 文件并检查中的值是否
documentCnt 属性匹配下的元素数量
返回数据节点。
如果您要在“ReturnData”元素上使用简单的 select 语句,则可以通过一个步骤解决此问题,如下所示:
public static void Main(params string[] args)
{
// test.xml contains OPs example xml.
var xDoc = XDocument.Load(@"c:\temp\test.xml");
// this will return an anonymous object for each "ReturnData" node.
var counts = xDoc.Descendants("ReturnData").Select((e, ndx) => new
{
// although xml does not have specified order this will generally
// work when tracing back to the source.
Index = ndx,
// the expected number of child nodes.
ExpectedCount = e.Attribute("documentCnt") != null ? int.Parse(e.Attribute("documentCnt").Value) : 0,
// the actual child nodes.
ActualCount = e.DescendantNodes().Count()
});
// now we can select the mismatches
var mismatches = counts.Where(c => c.ExpectedCount != c.ActualCount).ToList();
// and the others must therefore be the matches.
var matches = counts.Except(mismatches).ToList();
// we expect 3 matches and 0 mismatches for the sample xml.
Console.WriteLine("{0} matches, {1} mismatches", matches.Count, mismatches.Count);
Console.ReadLine();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)