My question is not about xpath syntax, it's related to the java API surrounding xpath. Consider the following xml:
<wrapper>
<metadata>
<somefield>somevalue</somefield>
<anotherfield>othervalue</anotherfield>
</metadata>
<data>
<some>
<unique>
<xml>
<structure>stuff</structure>
</xml>
</unique>
</some>
</data>
</wrapper>
I can easily get the metadata fields using xpath by using the following code:
XPath xp = XPathFactory.newInstance().newXPath();
Node node = (Node) xp.evaluate("/wrapper/metadata/somefield", xmlDoc, XPathConstants.NODE);
String somefield = node.getFirstChild().getNodeValue();
I am struggling with how I can get a string representing the subtree of xml starting with the <some>
tag. In other words, what code do I write to get a String that when printed out, would print out the following? The xpath query would be "/wrapper/data/some", but I do not know how to utilize the xpath api appropriately.
<some>
<unique>
<xml>
<structure>stuff</structure>
</xml>
</unique>
</some>
You simply need to transform the
Node
you get back from theXPathExpression
to aString
using aTransformer
as you would if you were writing the document to a file, here is a full example: