To parse an xml in java, we can make use of the JAXP – Java API for XML Parsing. The JAXP provides 2 standards which are SAX and DOM respectively. Here is the sample code which parses an xml using the DOM standard.
sample1.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <People> <Person> <Name>Alice</Name> <Gender>Female</Gender> <Age>23</Age> </Person> <Person> <Name>Bob</Name> <Gender>Male</Gender> <Age>25</Age> </Person> </People>
DomParser1.java
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DomParser1 { public static void main(String[] args) { System.out.println("*** Start ***"); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse("./sample1.xml"); Node parentNode = null; Node childNode = null; NodeList parentNodeList = null; NodeList childNodeList = null; parentNodeList = document.getElementsByTagName("Person"); for (int i = 0; i < parentNodeList.getLength(); i++) { parentNode = parentNodeList.item(i); childNodeList = parentNode.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { childNode = childNodeList.item(j); if (childNode.getNodeType() == Node.ELEMENT_NODE) { System.out.println(childNode.getNodeName() + ": " + childNode.getTextContent()); } } } } catch (Exception e) { e.printStackTrace(); } System.out.println("*** End ***"); } }
You can find the following text after running.
*** Start ***
Name: Alice
Gender: Female
Age: 23
Name: Bob
Gender: Male
Age: 25
*** End ***
nice article
LikeLike
Thanks =)
LikeLike
You may want to look at vtd-xml as the state of the art in XML processing, consuming far less memory than DOM
vtd-xml
LikeLike
Thanks~~ i will take a look on that later =)
LikeLike