Sunday, July 28, 2013

How to convert an XML file to DOM in Java

Create a org.w3c.dom.Document reference to the xml file, using this method:

public static Document filepathToDocument(final String filepath){
Document doc = null;
File file = new File(filepath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);  
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return doc;
}


Then, you can pretty much do anything like use XPath to navigate or simply get the list of Nodes:

XPath xPath =  XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile("//"+elemName).evaluate(doc, XPathConstants.NODESET);

// or

 NodeList nodeList = doc.getElementsByTagName(elemName);

// see www.w3schools.com to learn how to write xpath syntax.

No comments: