2015-04-07 41 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