XPath 查找所有匹配 C# XmlDocument [英] XPath find all matches C# XmlDocument

查看:26
本文介绍了XPath 查找所有匹配 C# XmlDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在 XmlDocument 中找到所有匹配的字符串.

I am trying to figure out how to find all matches of string in a XmlDocument.

XmlNodeList results 
      = document.SelectNodes("Products/Product/fn:matches(.,'" + SearchWord + "')");

我正在尝试比较 Product 的 innerText.

Im trying to compare the innerText of Product.

虽然上面的例子不起作用,但我想我使用 XPath 函数的方式非常错误.

The above example don't work though, but I guess my way of using XPath functions are very wrong.

推荐答案

评估这个 XPath 1.0 表达式(您知道 matches() 是一个 XPath 2.0 函数吗?.NET 中不支持):

Evaluate this XPath 1.0 expression (did you know matches() is an XPath 2.0 function and isn't supported in .NET):

Products/Product/descendant::*[contains(text(), 'YourSearchWord')]

这将选择具有包含字符串 'YourSearchWord' 的 text-node-child 的所有元素,并且这些元素是 Product 元素的后代,该元素是Products 元素,它是当前(上下文)节点的子节点.

This selects all elements that have a text-node-child that contains the string 'YourSearchWord' and that are descendents of a Product element that is a child of a Products element that is a child of the current (context) node.

您可以使用来编写 XPath 表达式:

You can compose the XPath expression with:

string.Format("Products/Product/descendant::*[contains(text(), '{0}')]", 
              SearchWord )

但是,如果 SearchWord 是从用户输入中获取的,建议不要将其包含在上述骨架字符串中,以避免 XPath 注入.

However, if SearchWord is obtained from user input, it is recommended never to include it in a skeletal string as above, so that XPath injection will be avoided.

如果是这种情况,推荐的方法是使用预编译的 XPath 表达式,在该表达式中,用户输入将作为变量被引用,并且该变量的值将从 XPath 评估上下文中使用.

If this is the case, the recommended method is to have a precompiled XPath expression in which the user input will be referenced as a variable and the value of this variable will be consumed from the XPath evaluation context.

可以在此答案中找到有关如何防止 XPath 注入的更多详细信息:

https://stackoverflow.com/a/6393690/36305

这篇关于XPath 查找所有匹配 C# XmlDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆