In Java, XML is represented with org.w3c.dom.Document
object. In this XML tutorial, we will learn to –
- Convert XML string to XML Document
- Convert XML file content to XML Document
1. Convert String to XML Document
To convert XML string to XML Dom, we need the following classes:
- javax.xml.parsers.DocumentBuilder : Defines the API to obtain XML DOM Document instances from XML content from various input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
- javax.xml.parsers.DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser (
DocumentBuilder
) that produces DOM object trees from XML content. - org.w3c.dom.Document : It represents the entire XML DOM. Conceptually, it is the root of the document tree, and provides the access to the document’s data further down into the tree, through factory methods.
- java.io.StringReader : Create a stream from String content.
DocumentBuilder
uses this stream to read XML content for parsing.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class ConvertStringToXML {
public static void main(String[] args) {
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
//Use method to convert XML string content to XML Document object
Document doc = convertStringToXMLDocument(xmlStr);
//Verify XML document is build correctly
System.out.println("Root Node : " + doc.getFirstChild().getNodeName());
NodeList nodeList = doc.getElementsByTagName("employee");
for (int itr = 0; itr < nodeList.getLength(); itr++) {
Node node = nodeList.item(itr);
System.out.println("\nNode Name : " + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
System.out.println("Name: "+ eElement.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Title: "+ eElement.getElementsByTagName("title").item(0).getTextContent());
}
}
}
private static Document convertStringToXMLDocument(String xmlString) {
//Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//API to obtain DOM Document instance
DocumentBuilder builder = null;
try {
//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
//Parse the content to Document object
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Program output:
Root Node : employees
Node Name : employee
Name: Lokesh Gupta
Title: Author
Node Name : employee
Name: Brian Lara
Title: Cricketer
2. Convert XML File to XML Document
To get the XML dom from XML file, instead of passing the XML string to DocumentBuilder, pass the file path to let the parser read the file content directly.
We have employees.xml
file which has XML content, we will read to get XML document.
<employees>
<employee id="101">
<name>Lokesh Gupta</name>
<title>Author</title>
</employee>
<employee id="102">
<name>Brian Lara</name>
<title>Cricketer</title>
</employee>
</employees>
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class StringtoXMLExample
{
public static void main(String[] args)
{
final String xmlFilePath = "employees.xml";
//Use method to convert XML string content to XML Document object
Document doc = convertXMLFileToXMLDocument( xmlFilePath );
//Verify XML document is build correctly
System.out.println(doc.getFirstChild().getNodeName());
}
private static Document convertXMLFileToXMLDocument(String filePath)
{
//Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//API to obtain DOM Document instance
DocumentBuilder builder = null;
try
{
//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
//Parse the content to Document object
Document doc = builder.parse(new File(filePath));
return doc;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
Drop me your questions in the comments section.
Happy Learning !!