Ever caught into a situation where you are required to create an object from your response XML? If yes, This post can be useful for you.
This tutorial shows you how to Convert String XML fragment to Document Node in Java. Consider the below example code:
/****************************************************************
* How to use turn an XML file into a document object in Java
****************************************************************/
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(
true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// Parse the XML file and build the Document object in RAM
Document doc = docBuilder.parse(
new StringBufferInputStream("<Name>JavaGenious</Name>));
// Normalize text representation.
// Collapses adjacent text nodes into one node.
doc.getDocumentElement().normalize();
The XML Nodelist can be obtained from this Document object which can be iterated using a Java for loop to read the enitre XML data. Moreover, You can use XPath to query the response XML using a XPath Expression. Know more about XPath in our, XPath Tutorial Section