c# - XPath 表达式求值错误

标签 c# .net xml

我尝试解析一个大的 XML 文件,并且我为 XPath 表达式使用了很多相对路径。

现在我遇到了 .net XPath 求值的问题。

这是一个解释我的问题的小例子:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
</book> 
</bookstore>

代码如下:

static void Main(string[] args)
{
    System.Xml.XmlDocument d = new System.Xml.XmlDocument();
    d.Load(@"D:\simpleXml.xml");

    System.Diagnostics.Trace.WriteLine(d.SelectSingleNode("//price/..[year=\'2005\']").Name);
}

我收到以下错误消息: 附加信息:'//price/..[year='2005']' 有一个无效的标记。

对我来说,它似乎是一个有效的 XPath 表达式,因为 XMLSpy 等其他工具可以成功评估该表达式。

最佳答案

为什么不用linq2xml

XDocument doc=XDocument.Load("yourXML");

var bookPrice=doc.Descendants("book")
.Where(x=>x.Element("year").Value=="2005")
.Select(y=>y.Element("price").Value);
//gets the price of the books published in 2005

如果你想要xpath版本,就在这里

"bookstore/book[year='2005']/*/../price"
//gets the price of the books published in 2005

关于c# - XPath 表达式求值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013401/

相关文章:

java - 如何获取 XmlType 的字符串表示形式?

java - 属性的 XSLT 格式-日期

c# - 将继承的 NHibernate-Object 转换为另一个从同一基础继承的对象

c# - 为什么我的 DTO 为空?

c# - MVVM WPF 保存和加载用户设置设计模式

c# - 如何在 C# 中更改 XML 文件的属性值?

c# - 如何检查对象的一个​​值是否为 null

c# - 在 EF 核心中具有唯一性的备用键和 HasIndex 之间的真正区别是什么?

c# - int 和 long 类型的方法重载,哪个方法将被调用以及何时调用?

asp.net - 在发布时更改 .config 文件中的附加程序参数值( azure 管道)