使用XPath访问扁平结构中的注释

3

我有一个指定的XML文档(结构不能更改),想要获取写在节点上方的注释。该文档如下:

<!--Some comment here-->    
    <attribute name="Title">Book A</attribute>
    <attribute name="Author">
       <value>Joe Doe</value>
       <value>John Miller</value>
    </attribute>
<!--Some comment here-->
    <attribute name="Code">1</attribute>

因此,注释是可选的,但如果有注释,我希望在每个属性上方获取注释。 使用 / * / comment()[n] 会给我第n个注释,但对于n = 2,我自然会得到第三个属性的注释,因此属性和注释之间没有连接。 有什么想法?谢谢
2个回答

1
如果您想选择后跟有 attribute 元素的注释,则应该使用以下代码:
/*/comment()[following-sibling::*[position()=1 and name()='attribute']]

0

使用方法:

//comment()[following-sibling::*[1][self::attribute]]

这比当前选择的答案更紧凑和精确// 缩写是必要的,因为没有提供格式良好的 XML 文档,并且注释节点的嵌套级别未知。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接