2013-08-22 110 views
0

有沒有一種很好的方式在c#中查看使用DOM的XML節點列表並獲取僅包含唯一節點的節點列表以及每個節點的唯一可能屬性列表。獨特的節點和c#

有問題的XMl文件具有相同名稱但具有不同屬性的節點,我想要一個所有可能的列表。此外,我希望只有唯一節點的節點列表,而不是重複節點列表(因此我生成的節點列表可能有兩次接觸,三次接觸)。它需要適用於任何XML文檔。有任何想法嗎?

下面是一個例子:

<book id="bk112"> 
    <author>Galos, Mike</author> 
    <title>Visual Studio 7: A Comprehensive Guide</title> 
    <genre>Computer</genre> 
    <price>49.95</price> 
    <publish_date>2001-04-16</publish_date> 
</book> 
<book id="bk162"> 
    <genre>fiction</genre> 
    <popularity>High</popularity> 
    <price>20.00</price> 
    <publish_date>2002-03-12</publish_date> 
</book> 
<cd id="bk162"> 
    <genre>jaz</genre> 
    <popularity>High</popularity> 
    <price>10.00</price> 
</cd> 

,並得到一些有點像輸出:

there are 2 of the type book 
there are 1 of the type cd 
there are 3 of the type genre 
book may have the attributes author, title, genre, price, popularity, publish_date 

但是,對於任何XML文件的工作方式。

在流派的情況下,它不需要任何方式,只要知道文檔中有3個流派節點。

+0

示例xml和預期的輸出和ofcourse你有什麼試過? – Ehsan

+0

請參閱'HtmlAgilityPack','IEqualityComparer '。 –

+0

您能發佈一個示例XML來使您的問題更清晰嗎?什麼被認爲是獨特的?即。如果聯繫節點出現在XML文檔的不同級別,它是否仍然是重複的? – aaroncatlin

回答

0

會這樣做嗎?

XDocument xDoc = XDocument.Load("XMLFile1.xml"); 
List<XElement> distinctDocs = xDoc.Descendants().GroupBy(x => x.Name).Where(x => x.Count() == 1).Select(g => g.Single()).ToList(); 
+0

不要這麼想,除非我失去了一些東西。我沒有節點的名稱,直到運行時 – user2707220

+0

@ user2707220此解決方案不需要您在運行時具有任何名稱。爲什麼不運行它,設置突破口,並檢查'​​distinctDocs' var –

+0

@ user2707220中的內容我編輯了我的答案以避免類型混淆。試用一下 –