Using XPath to access comments a flat hierachy

霸气de小男生 提交于 2019-12-13 14:43:33

问题


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


回答1:


Use:

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

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.




回答2:


If you want to select the comments that are followed by an attribute element, then this should work:

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


来源:https://stackoverflow.com/questions/2636192/using-xpath-to-access-comments-a-flat-hierachy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!