Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XPath to access comments a flat hierachy

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

like image 384
Sebastian Avatar asked Aug 22 '26 21:08

Sebastian


1 Answers

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']]
like image 130
Mads Hansen Avatar answered Aug 24 '26 12:08

Mads Hansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!