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.
importjava.io.StringReader;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importorg.xml.sax.InputSource;publicclassConvertStringToXML{publicstaticvoidmain(String[] args){finalString 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 objectDocument doc =convertStringToXMLDocument(xmlStr);//Verify XML document is build correctlySystem.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());}}}privatestaticDocumentconvertStringToXMLDocument(String xmlString){//Parser that produces DOM object trees from XML contentDocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();//API to obtain DOM Document instanceDocumentBuilder builder =null;try{//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();//Parse the content to Document objectDocument doc = builder.parse(newInputSource(newStringReader(xmlString)));return doc;}catch(Exception e){
e.printStackTrace();}returnnull;}}
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.
importjava.io.File;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importorg.w3c.dom.Document;publicclassStringtoXMLExample{publicstaticvoidmain(String[] args){finalString xmlFilePath ="employees.xml";//Use method to convert XML string content to XML Document objectDocument doc =convertXMLFileToXMLDocument( xmlFilePath );//Verify XML document is build correctlySystem.out.println(doc.getFirstChild().getNodeName());}privatestaticDocumentconvertXMLFileToXMLDocument(String filePath){//Parser that produces DOM object trees from XML contentDocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();//API to obtain DOM Document instanceDocumentBuilder builder =null;try{//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();//Parse the content to Document objectDocument doc = builder.parse(newFile(filePath));return doc;}catch(Exception e){
e.printStackTrace();}returnnull;}}
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments