XML parsing in Java

java

http://www.totheriver.com/learn/xml/xmltutorial.html
http://www.cafeconleche.org/books/xmljava/chapters/
http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Element.html
http://java.sun.com/developer/Books/xmljava/ch03.pdf
http://www.javaworld.com/article/2076189/enterprise-java/book-excerpt--converting-xml-to-spreadsheet--and-vice-versa.html
https://dzone.com/articles/solving-the-xml-problem-with-jackson

How can we extract information out of an XML file or node?

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlDocument);

NodeList nodeList = document.getElementsByTagName("tagName");
cell.setCellValue(
    (
        (Element) (nodeList.item(0))).
            getElementsByTagName("revenue").
            item(0).getFirstChild().getNodeValue()
);

We can then use document.getElementsByTagName, item, getFirstChild, getNodeValue, or other DOM traveral methods that are commonly used to traverse HTML DOM to poke at the XML nodes.

How can we create an XML file?

import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("rootElementTagName");
document.appendChild(rootElement);

We can use document.createElement, appendChild, document.createTextNode, and other DOM traversal methods that are commonly used to create HTML DOM and attributes to create the XML DOM. And then we can output the XML DOM to a file or System.out:

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document)
StreamResult result = new StreamResult(new File(System.out));
transformer.transform(source, result);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License