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,我自然会得到第三个属性的评论,所以属性和评论之间没有联系有什么想法吗?谢谢

4

2 回答 2

1

如果要选择attribute元素后面的注释,那么这应该有效:

/*/comment()[following-sibling::*[position()=1 and name()='attribute']]
于 2010-04-14T11:32:08.863 回答
0

使用

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

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

于 2010-04-14T13:11:30.627 回答