使用 XPath 访问扁平化层次结构的评论
我有一个给定的 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 我自然会得到第三个属性的注释,因此属性和注释之间没有任何联系? 谢谢
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>
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想选择后面跟着
attribute
元素的注释,那么这应该可行:If you want to select the comments that are followed by an
attribute
element, then this should work:使用:
这比当前选择的答案更紧凑、更精确。
//
缩写是必要的,因为没有提供格式良好的 XML 文档,并且注释节点的嵌套级别未知。Use:
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.