[JAVA] Read XML data

For reading XML file, there are several approaches to do so, if reading XML node element, it can use Java.xml in an old school approach.

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
 // Initial XML stream setting.
 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
 Document document = docBuilder.parse(new File("document.xml"));
 // Loop all nodes inside Element "*".
 NodeList nodeList = document.getElementsByTagName("*");
 for (int i = 0; i < nodeList.getLength(); i++) {
  Node node = nodeList.item(i);
  if (node.getNodeType() == Node.ELEMENT_NODE) 
  { // do something with the current element
    System.out.println(node.getNodeName());
 }
 }
 }

Reference:

http://stackoverflow.com/questions/5386991/java-most-efficient-method-to-iterate-over-all-elements-in-a-org-w3c-dom-docume


Revision at 01-Dec-2021:

It can read file and map to object directly with JAXB API.

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public TestResult read(File file) {
  try {
            JAXBContext jaxbTestResultsContext = JAXBContext.newInstance(TestResults.class);
            Unmarshaller jaxbTestResultUnmarshall = jaxbTestResultsContext.createUnmarshaller();
            return (TestResults) jaxbTestResultUnmarshall.unmarshal(file);
        } catch (JAXBException exception) {
            throw new ReportResolveException("Error occurred when initial JAXB object with Test results.", exception);
        }
}

 

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.