【问题标题】:XPath query works with online tools but not in .NETXPath 查询适用于在线工具,但不适用于 .NET
【发布时间】:2013-01-26 01:59:41
【问题描述】:

我可以使用在线 xpath 工具使下面的 xpath 与下面的 xml 一起工作,但我得到一个“表达式必须评估为节点集”。 .NET 4.5 中的异常

xpath:

//*[starts-with(name(.), "childnode")[identification/text()='xyz']]

xml:

<rootnode>
    <childnode1234>
        <identification>xyz</identification>
    </childnode1234>
    <childnode3456>
        <identification>abc</identification>
    </childnode3456>
 </rootnode>

预期的结果是

<childnode1234>
            <identification>xyz</identification>
        </childnode1234>

【问题讨论】:

  • 您使用哪些在线工具?他们返回什么?
  • 您是否正确复制了 XPath?最后的"; 是什么意思?
  • 请显示真实的 C# string - 现在它包含非转义双引号...
  • 我试过的测试人员是:xpathtester.com/test & freeformatter.com/xpath-tester.html。我正在转义“ with \”。预期结果是:xyz

标签: c# .net xml xpath


【解决方案1】:

只需改变:

//*[starts-with(name(.), "childnode")[identification/text()='xyz']]

//*[starts-with(name(.), "childnode")][identification/text()='xyz']

我建议避免使用未经测试且明显有问题的“无名”“在线 xpath 工具”

【讨论】:

  • @RossPatterson,是的,其中有很多吸引了新手——只是发现它们不符合 XPath 实现。
【解决方案2】:

网上的实现太宽松了。 Microsoft XPath 是正确的:starts-with() 计算为布尔值,而不是节点集。试试

//*[starts-with(name(.), 'childnode') and identification/text()='xyz']

【讨论】:

  • +1 因为我认为//*[x and y] 在风格上比//*[x][y] 更可取,尽管它们是等价的。
猜你喜欢
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 2011-05-20
  • 2020-04-13
  • 1970-01-01
相关资源
最近更新 更多