2010-09-11 93 views
2

我一直試圖在C#麻煩解析使用LINQ深層嵌套的屬性,以XML

<schema uri=http://blah.com/schema > 
    <itemGroups> 
    <itemGroup description="itemGroup1 label="itemGroup1"> 
     <items> 
     <item description="The best" itemId="1" label="Nutella"/> 
     <item description="The worst" itemId="2" label="Vegemite"/> 
     </items> 
    </itemGroup> 
    </itemGroups> 
</schema> 

\itemGroup1\Nutella-The best 
\itemGroup1\Vegemite-The worst 

任何幫助或方向來解析這個XML,將不勝感激。

回答

6
XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream 

var rows = xDoc.Descendants("item").Select(x => string.Format(
        @"\{0}-{1}\{2}-{3}", 
        x.Ancestors("itemGroup").First().Attribute("description").Value, 
        x.Ancestors("itemGroup").First().Attribute("label").Value, 
        x.Attribute("label").Value, 
        x.Attribute("description").Value)); 

讓我們打破我們正在做的事情:

  • xDoc.Descendants("item")得到我們整個文檔中的所有<item>元素

  • Select(x => string.Format(format, args)項目每個<item>我們從最近的操作了轉換成我們在lambda中指定的格式。在這種情況下,一個formatted string

  • 就XML樹而言,我們「坐在」<item>級別,因此我們需要回滾樹狀圖,以使用Ancestors獲取父組的數據。由於該方法返回一系列元素,我們知道我們需要第一個(離我們最近的),以便我們可以讀取它的屬性。

現在,你有你的XML文檔中的IEnumerable<string>,每個<item>,並在您指定的格式的信息:

foreach(string row in rows) 
{ 
    Console.WriteLine(row); 
} 
+0

非常感謝!從未解析過xml,你的解釋非常有幫助。乾杯 – smashbourne 2010-09-12 05:30:54