Using XPath to access comments in a flat hierarchy

I have an XML document (the structure cannot be changed) and I want to get comments written over the nodes. The document is as follows:

<!--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>

Thus, comments are optional, but if they are, I want to get a comment above each attribute. Using /*/comment()[n]will give me a comment n, but for n = 2 I would naturally get a comment from the third attribute, so there is no connection between the attributes and the comments. Any ideas? thank

+3
source share
2 answers

Using

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

, . // , XML-, .

0

, attribute, :

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

Source: https://habr.com/ru/post/1741058/


All Articles