解析嵌套 XML
Parsing nested XML
这似乎是一项非常基本的任务,我想知道我是否使用了错误的搜索词,因为我没有找到解决这个问题的方法...
我有一个非常简单的嵌套 XML:
<books>
<book>
<author>Douglas Adams</author>
<title>The Hitch Hikers Guide to the Galaxy</title>
<price>42</price>
</book>
</books>
我是WebAPI获取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 and am trying to understand how to navigate the DOM tree。恐怕我不明白术语 nodes
、child
。非常感谢任何帮助:-)
使用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
可能会引发死锁错误 - 使用 "correct" 等待方法
var result = await ReadAsStreamAsync();
这似乎是一项非常基本的任务,我想知道我是否使用了错误的搜索词,因为我没有找到解决这个问题的方法...
我有一个非常简单的嵌套 XML:
<books>
<book>
<author>Douglas Adams</author>
<title>The Hitch Hikers Guide to the Galaxy</title>
<price>42</price>
</book>
</books>
我是WebAPI获取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 and am trying to understand how to navigate the DOM tree。恐怕我不明白术语 nodes
、child
。非常感谢任何帮助:-)
使用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
可能会引发死锁错误 - 使用 "correct" 等待方法
var result = await ReadAsStreamAsync();