【问题标题】:Getting the count of xml elements under an XML Node获取 XML 节点下 xml 元素的计数
【发布时间】:2015-04-07 00:06:49
【问题描述】:

我希望获取 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>

我需要为 ReturnData 节点解析这个 xml 文件(如您所见,该节点位于文件中的多个位置)并获取其下方元素的计数。

例如 - 在 Return\ReturnData 下,计数必须为 8 - 在 Return\ParentReturn\ReturnData 下,计数必须为 6 - 在 Return\SubsidiaryReturn\ReturnData 下,计数必须为 3

documentCnt 属性实际上应该给我正确的计数,但是创建的 xml 文档会有差异,因此我需要解析这个 xml 文件并检查 documentCnt 属性中的值是否与 ReturnData 下的元素数匹配节点。

【问题讨论】:

标签: c# xml


【解决方案1】:

使用您给出的问题描述:

属性 documentCnt 实际上应该给我正确的计数但是 创建的 xml 文档会有差异,因此我 将需要解析这个 xml 文件并检查 documentCnt 属性匹配下的元素个数 ReturnData 节点。

如果您要在“ReturnData”元素上使用简单的选择语句,这可以一步解决,如下所示:

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();
}

【讨论】:

  • 非常感谢亚历克斯。绝妙的答案!!
猜你喜欢
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
相关资源
最近更新 更多