gpt4 book ai didi

c# - XPathNodeIterator 从迭代数据访问子节点

转载 作者:数据小太阳 更新时间:2023-10-29 02:15:55 25 4
gpt4 key购买 nike

<?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)
{
??
}

最佳答案

使用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);
}

关于c# - XPathNodeIterator 从迭代数据访问子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com