2015-04-07 43 views
0

我正在寻找获取XML文件中特定节点下的元素的数量。在XML节点下获取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文件获得的数它下面的元素。

例如 - 在返回\ ReturnData计数必须是8 - 在返回\ ParentReturn \ ReturnData计数必须是6 - 在返回\ SubsidiaryReturn \ ReturnData计数必须是3

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

如果你们能帮助我,我会很感激。

感谢, AJ

+0

请参阅本http://stackoverflow.com/questions/2287384/count-specific-xml-nodes-within-xml –

+0

感谢您的回复Saagar! – user3375390

回答

1

使用问题说明你给了:

属性documentCnt实际上应该给我正确的计数,但 时生成会有差异XML文档,因此我 将需要解析此xml文件,并检查 documentCnt属性中的值是否与返回数据节点的 下的元素数相匹配。

这可以在一个单一的步骤来解决,如果你使用一个简单的SELECT语句的“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(); 
} 
+0

非常感谢Alex。辉煌的答案! – user3375390