这似乎是一项非常基本的任务,我想知道我是否使用了错误的搜索词,因为我找不到解决方案......
我有一个非常简单的嵌套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,所以我不确定如何遍历 title属性。
我读到了XPath,并试图了解如何navigate the DOM tree。我恐怕没有得到术语nodes
,child
。非常感谢任何帮助: - )
答案 0 :(得分: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();