如何使用 Linq 执行此 XPath 查询?
在下面的代码中,我使用 XPath 来查找所有使用 XPath 匹配的节点,并将这些值附加到 StringBuilder。
StringBuilder sb = new StringBuilder();
foreach (XmlNode node in this.Data.SelectNodes("ID/item[@id=200]/DAT[1]/line[position()>1]/data[1]/text()"))
{
sb.Append(node.Value);
}
return sb.ToString();
除了使用 Linq to XML 之外,我该如何做同样的事情?假设在新版本中,this.Data是一个XElement对象。
In the following code I am using XPath to find all of the matching nodes using XPath, and appending the values to a StringBuilder.
StringBuilder sb = new StringBuilder();
foreach (XmlNode node in this.Data.SelectNodes("ID/item[@id=200]/DAT[1]/line[position()>1]/data[1]/text()"))
{
sb.Append(node.Value);
}
return sb.ToString();
How do I do the same thing, except using Linq to XML instead? Assume that in the new version, this.Data is an XElement object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您仍然可以将 XPath 与 XElement 结合使用。您必须包含 System.Xml.XPath 命名空间,因为它是扩展方法
You can still use XPath with a XElement. You have to include the System.Xml.XPath namespace since its an extension method
查询语法看起来像这样。
...这将消除可能的 nullref 异常,并消除
foreach
循环。Query syntax would look something like this.
... this would get rid of the possible nullref exceptions and would get rid of the
foreach
loop.您可以尝试类似的方法:
如您所见,它并不比 XPath 更方便,因此您应该继续使用 XPath (如 Pierre-Alain 的回答中所述)
You can try something like that :
As you can see, it's not really more convenient than XPath, so you should probably keep using XPath (as explained in Pierre-Alain's answer)
我创建了一个开源帮助程序库,可让您使用 Linq-esq 表达式生成 xpath 表达式。不确定它对您的上下文是否有帮助,但将链接发布到 API
http://www.syntaxsuccess.com/viewarticle/how-to-create-xpath-using-linq
I have created an open source helper library that let's you generate xpath expressions using Linq-esq expressions. Not sure if it is helpful in your context, but posting the link to the API
http://www.syntaxsuccess.com/viewarticle/how-to-create-xpath-using-linq