If say I’ve got the following XML file:
<title text=“title1">
<comment id=“comment1">
<data> this is part of comment one</data>
<data> this is some more of comment one</data>
</comment>
<comment id=“comment2”>
<data> this is part of comment two</data>
<data> this is some more of comment two</data>
<data> this is even some more of comment two</data>
</comment>
</title>
And I’m given the following XPath query:
/title/comment/@id
What would be the best way to get the subtree to which the expression belongs.
So for instance, the above expression would return:
id="comment1"id="comment2"
To which, comment1 belongs to subtree:
<comment id="comment1">
<data> this is part of comment one</data>
<data> this is some more of comment one</data>
</comment>
And, comment2 belongs to subtree:
<comment id=“comment2">
<data> this is part of comment two</data>
<data> this is some more of comment two</data>
<data> this is even some more of comment two</data>
</comment>
The reason I want this is so that I can recursively make a call on the sub-tree where the Xpath expression is resolved to.
I am coding this in Java using DOM.
It sounds like the XPath expression is unknown until run time.
And you want to obtain the parent of each node selected by the XPath expression… is that right? The
<comment>element is the parent of eachcomment/@idattribute. Obtaining the<comment>element is equivalent to obtaining its subtree (descendants), because you can extract its descendants using further XPath expressions or DOM functions, or you can copy the<comment>element with its descendants.One way to answer your question then is to simply append “/..” to the end of the XPath expression. E.g.
would become
which is equivalent to @Dan’s answer, but can be easily derived from whatever the XPath expression may be.