I have a XML like below and i am reading the XML using XPath . Since i know the exact location where the data will be , i am passing the path dynamically to the Expression object and getting the values.
<MESSAGE xmlns:xlink="http://www.w3.org/1999/xlink">
<ABOUT_VERSIONS>
<ABOUT_VERSION SequenceNumber="1" xlink:label="ASSET_1" >
<CreatedDatetime>2015-08-24T09:30:47Z</CreatedDatetime>
<DataVersionName>Purchase Example</DataVersionName>
</ABOUT_VERSION>
</ABOUT_VERSIONS>
<DEALS>
<DEAL>
<ACCOUNT>
<Name>Test</Name>
</ACCOUNT>
</DEAL>
</DEALS>
</MESSAGE>
I am using below kind of code to read the XML.
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
XPathExpression pathExpression =
xPath.compile("MESSAGE/ABOUT_VERSIONS/ABOUT_VERSION");
InputSource inputSource = new InputSource("C:/Sample.xml");
NodeList Nodes = (NodeList)
xPath.evaluate("MESSAGE/ABOUT_VERSIONS/ABOUT_VERSION", inputSource,
XPathConstants.NODESET);
Is there such kind of way to write XML in Java ? I need to write same XML with additional tags and extra data later.
XPath itself is a pattern matching language, like regular expressions, so you can't use it directly to do manipulation. But like regular expressions there are engines that allow you to use XPath as part of a larger technology stack to modify documents.
If you're trying to modify an existing XML document, you should look into reading it as a DOM tree. You can then use XPath to easily find individual nodes or groups of nodes that you want to modify. Modify them using the DOM model and then serialize it back out to disk.
Alternatively you can create an XSLT sheet to transform the input. You can start with the identity transformation, which looks like this...
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
That will produce the same XML output as your input document. You can then start adding templates to modify particular nodes matching your desired XPaths. This tends to be significantly harder to do, in my experience, than DOM manipulation, because most of the logic that you'd normally do in Java you now have to do in XSLT, which it it's own language. However, since you can do XSLT transformation with streaming, it's sometimes easier if you're working with very large documents that will be hard to fit in memory.
I'd offer more details, but I honestly haven't worked with any of this for like 6 years, so I'm a little rusty on the syntax.