2017-03-27 124 views
0

這似乎是一個非常基本的任務,我如果我使用了錯誤的搜索詞,因爲我沒有找到一個解決這個疑惑...解析嵌套的XML

我有一個非常簡單的,嵌套的XML:

<books> 
    <book> 
     <author>Douglas Adams</author> 
     <title>The Hitch Hikers Guide to the Galaxy</title> 
     <price>42</price> 
    </book> 
</books> 

我在Web API來獲取XML內容返回到一個流,用可變xmlStream上面粘貼的內容結束:

var xmlStream = response.Content.ReadAsStreamAsync().Result; 
var xmlDocument = new XmlDocument(); 

xmlDocument.Load(xmlStream); 

Console.WriteLine("Title:"); 
// Do something to get the value of 'title' 
Console.WriteLine(xmlDocument.someTraversion...); 

因爲我還沒有和XML睦工作h我不確定如何遍歷標題屬性

我讀了關於XPath,並試圖瞭解如何navigate the DOM tree。恐怕我沒有得到術語nodeschild。任何幫助是極大的讚賞:-)

+0

我不介意downvoted,但將不勝感激評論什麼改善我的問題:-) – jrn

+1

至於術語,「孩子」將是一個元素是在另一個元素。在這種情況下,'Author'是'Book'的子元素,它是'Books'的子元素。從「書籍」的角度來看,「作者」不是孩子,而是祖先。 「節點」是XML的任何語法部分,整個文檔是節點,單個元素是節點,屬性是節點等。 –

+0

非常感謝@BradleyUffner!這現在更有意義了:-) – jrn

回答

1

使用LINQ of XML

XElement document = null; 
using (var stream = await response.Content.ReadAsStreamAsync()) 
{ 
    document = XElement.Load(stream); 
} 

foreach(var book in document.Descendants("book")) 
{ 
    var title = book.Element("title").Value; 
    // use title 
} 

注意使用ReadAsStreamAsync().Result都不可能拋出一個死鎖錯誤 - 用「正確」的方式等待

var result = await ReadAsStreamAsync(); 
+0

非常感謝您的幫助法比奧!我收到以下錯誤消息:'XmlElement'不包含'Load'定義 – jrn

+0

'XDocument'和'XElement'應該是'XmlDocument'和'XmlElement'嗎? – jrn

+1

@jrn,no。 XDocument是System.Xml.Linq中的類。 – Fabio