【问题标题】:Selecting different types of nodes or NULL values with XPATH使用 XPATH 选择不同类型的节点或 NULL 值
【发布时间】:2016-01-28 09:07:59
【问题描述】:

假设我们有以下 xml 结构:

<root>
   <nodeA>
     <nodeB>Some text</nodeB>
   </nodeA>
   <nodeA>Some text</nodeA>
   <nodeA>
     <nodeB>Some other text</nodeB>
   </nodeA>
   ...
</root>

有没有办法为每个nodeA选择“nodeB”节点或NULL值,所以对于上面的例子它返回:

nodeB
NULL
nodeB

元素的顺序很重要。

谢谢!

【问题讨论】:

  • 在 XPath 1.0 以上的版本中有什么方法吗?

标签: xml xpath


【解决方案1】:

在 XPath 2.0 中,您可以像这样使用 for 循环和 if 语句:

for $a in //nodeA 
return 
    if($a/nodeB) then $a/nodeB 
    else 'NULL'

在线测试here,并给定输入 XML 作为发布的有问题的输出是想要的:

Some text
NULL
Some other text

【讨论】:

  • 感谢您提供此解决方案!我找到了这个库:xpath2.codeplex.com,但不确定我们是否可以使用它来查询 IE 中的 DOM 元素。
猜你喜欢
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
相关资源
最近更新 更多