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

Xml 使用XPath访问扁平层次结构中的注释,xml,xpath,comments,xml-comments,Xml,Xpath,Comments,Xml Comments,我有一个给定的XML文档(结构无法更改),并希望获得写在节点上方的注释。该文档如下所示: <!--Some comment here--> <attribute name="Title">Book A</attribute> <attribute name="Author"> <value>Joe Doe</value> <value>John Miller&l

我有一个给定的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>

预订
乔·多伊
约翰·米勒
1.
因此,注释是可选的,但是如果有注释,我希望在每个属性上方获得注释。 使用
/*/comment()[n]
会给我注释n,但对于n=2,我自然会得到第三个属性的注释,因此属性和注释之间没有联系。有什么想法吗?
谢谢

如果要选择后跟
属性的注释
元素,那么这应该可以:

/*/comment()[following-sibling::*[position()=1 and name()='attribute']]
使用

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

这比当前选择的答案更简洁、更精确。
/
缩写是必要的,因为没有提供格式良好的XML文档,注释节点的嵌套级别也不知道。

太好了,这正是我想要的。非常感谢。