Using this XML example:
<A>
<B>
<id>0</id>
</B>
<B>
<id>1</id>
</B>
</A>
I want a simple method to extract the XML block of node B, returning the XML String:
<B>
<id>1</id>
</B>
To retrieve this node i should use some Java XPath library like XOM or Java XPath, but i couldn't find how to get the complete XML string.
I found two equivalent answered questions using C#: C# How to extract complete xml node set and how can I extract an XML block from an XML document?
The expression needed to refer to that second
B
element should look something like this:Or, if the target node is at an unknown position in the document, use:
Full Java example (assuming the XML is in a file called
workbook.xml
):Adding to lwburk's solution, to convert a DOM Node to string form, you can use a Transformer:
Complete example: