问题描述
我有一个给定的XML文档(结构不能更改),并想获得在节点上面写的注释。文档如下所示:
I have a given XML document (structure can not be changed) and want to get the comments that are written above the nodes. The document looks like this:
<!--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我自然会得到第三个属性的注释,有没有属性和评论之间的任何想法?
感谢
So comments are optional, but if there is one, I want to get the comment above each attribute. Using /*/comment()[n]
would give me comment n, but for n=2 I would naturally get the comment of the third attribute, so there is no connection between attributes and comments Any ideas?Thanks
推荐答案
使用:
//comment()[following-sibling::*[1][self::attribute]]
这比当前选择的答案更紧凑和精确。 //
缩写是必要的,因为未提供格式良好的XML文档,并且注释节点的嵌套级别未知。
This is more compact and precise than the currently selected answer. The //
abbreviation is necessary, since no wellformed XML document was provided and the nesting level of the comment nodes is not known.
这篇关于使用XPath访问评论一个扁平的hierachy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!