【问题标题】:C#: XPath to select node with attribute containing a substring?C#:XPath 选择具有包含子字符串的属性的节点?
【发布时间】:2009-11-23 09:14:48
【问题描述】:

我可以使用 XPath 来选择代码包含 UK 的国家节点吗?

<country-list>
  <Country code="TW,UK,MY" />
  <Country code="US,CA,MX" />
  <Country code="IN,PR,VI,IR" />
  <Country code="Others" /> 
</country-list>

谢谢。

【问题讨论】:

  • 只是好奇为什么在答案并没有真正解决您的问题时您接受了答案?

标签: c# asp.net xpath c#-2.0


【解决方案1】:

试试contains() XPath 函数。

类似:

/Country[fn:contains(@code, "UK")]

快速的 Google 搜索可以找到 XPath 函数的详细信息: http://www.w3schools.com/xpath/xpath_functions.asp

【讨论】:

  • 您好,我遇到了这个错误:[System.Xml.XPath.XPathException] = {"Namespace Manager or XsltContext required. This query has a prefix, variable, or user-defined function."} 如何我可以绕过它吗?
  • 这是 'fn:' 命名空间前缀。尝试删除它。
【解决方案2】:

你需要这样写:

/country-list/Country[contains(@code,'UK')]

【讨论】:

    【解决方案3】:

    您可以使用 Linq to XML - 只是一个想法

    类似这样的:

    var countryElement = from country in countryElement.GetAttribute("code")
      where country.Value.Contains("UK")
      select countryElement;
    

    【讨论】:

      【解决方案4】:

      是的,做类似的事情

      //Country[contains(@code, 'UK')]
      

      选择了第一个 Country 元素

      【讨论】:

        最近更新 更多