<?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>
我从xml文件中选择了所有书籍。如何使用XPath为每本书选择标题,作者(名字和姓氏)和价格?
xPathDoc = new XPathDocument(filePath);
xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator book in xPathIterator)
{
??
}
答案 0 :(得分:9)
使用SelectSingleNode()
和Value
:
XPathDocument xPathDoc = new XPathDocument(filePath);
XPathNavigator xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator book in xPathIterator)
{
XPathNavigator nav = book.SelectSingleNode("title");
string title = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("author/first-name");
string authorFirstName = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("author/last-name");
string authorLastName = nav==null ? string.Empty : nav.Value;
nav = book.SelectSingleNode("price");
string price = nav==null ? string.Empty : nav.Value;;
Console.WriteLine("{0} {1} {2} {3}", title, authorFirstName, authorLastName, price);
}
答案 1 :(得分:3)
您可以使用LINQ2XML
XElement doc=XElement.Load("yourXML.xml");//loads your xml
var bookList=doc.Descendants().Elements("book").Select(
x=>//your book node
new{
title=x.Element("title").Value,
author=new //accessing your author node
{
firstName=x.Element("author").Element("first-name").Value,
lastName=x.Element("author").Element("last-name").Value
},
price=x.Element("price").Value
}
);
bookList
现在拥有您想要的所有元素
所以,你现在可以这样做
foreach(var book in bookList)
{
book.title;//contains title of the book
book.author.firstName;//contains firstname of that book's author
book.author.lastName;
}
答案 2 :(得分:0)
我喜欢Mimo提供的解决方案,但只需稍加改动,创建一个扩展方法来重用部分功能:
public static class XPathNavigatorExtensions
{
public static string GetChildNodeValue(this XPathNavigator navigator, string nodePath)
{
XPathNavigator nav = navigator.SelectSingleNode(nodePath);
return nav == null ? string.Empty : nav.Value;
}
}
结果代码看起来更干净:
ICollection<Book> books = new List<Book>();
foreach (XPathNavigator node in iterator)
{
Book book = new Book() { Author = new Author() };
book.Title = node.GetChildNodeValue("title");
book.Author.FirstName = node.GetChildNodeValue("author/first-name");
book.Author.LastName = node.GetChildNodeValue("author/last-name");
book.Price = node.GetChildNodeValue("price");
books.Add(book);
}