<?xml version="1.0"?>
-<bookstore>
<book >
<title>aaaa</title>
-<author >
<first-name>firts</first-name>
<last-name>last</last-name>
</author>
<price>8.23</price>
<otherbooks>
<book >
<title>bbb</title>
<price>18.23</price>
</book>
<book >
<title>ccc</title>
<price>11.22</price>
</book>
</otherbooks>
</book>
</bookstore>
我想选择不同级别的所有书籍,然后显示每个书籍(作者,标题和价格)的信息。目前代码还会显示第一本书的其他书籍。什么是仅显示所需信息的最佳方式。 我需要使用XPath。
xPathDoc = new XPathDocument(filePath);
xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator navigator in xPathIterator)
{
XPathNavigator clone = navigator.Clone();
clone.MoveToFirstChild();
Console.WriteLine(clone.Name + " : " + clone.Value);
while (clone.MoveToNext())
{
Console.Write(clone.Name + " : " + clone.Value + " | ");
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
如果您愿意尝试使用Linq To Xml:
var xDoc = XDocument.Parse(xml); //or XDocument.Load(filename)
var books = xDoc.Root.Elements("book")
.Select(b => new
{
Author = b.Element("author").Element("first-name").Value + " " +
b.Element("author").Element("last-name").Value,
Books = b.Descendants("book")
.Select(x => new
{
Title = x.Element("title").Value,
Price = (decimal)x.Element("price"),
})
.Concat(new[] { new { Title = b.Element("title").Value,
Price = (decimal)b.Element("price") }
})
.ToList()
})
.ToList();