Startseite bisherige Projekte Tools/Snippets Bücherempfehlungen Publikationen Impressum Datenschutzerklärung

XML UtilitiesApril 2015

Basic Utilities for writing XML files with Java.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

/**
 * Helper class for working with XML data.
 */
public class XMLUtils {

    public static Document createDocument(){
        try{
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
            return doc;
        }
        catch (ParserConfigurationException e){
            // will not happen
            return null;
        }
    }
    
    public static Element createElement(Document doc, String name){
        Element element = doc.createElement(name);
        return element;
    }
    
    public static Element addElement(Node n, String name){
        Element elem = createElement(getDocument(n), name);
        n.appendChild(elem);
        return elem;
    }

    private static Document getDocument(Node n) {
        if (n instanceof Document){
            return (Document)n;
        }
        return n.getOwnerDocument();
    }
    
    public static Element addElementWithText(Node n, String elementName, String text){
        Element elem = createElement(getDocument(n), elementName);
        Text t = createTextNode(getDocument(n), text);
        elem.appendChild(t);
        n.appendChild(elem);
        return elem;
    }
    
    public static Text createTextNode(Document doc, String text){
        Text textNode = doc.createTextNode(text);
        return textNode;
    }
    
    public static Text addTextNode(Node n, String text){
        Text textNode = createTextNode(getDocument(n), text);
        n.appendChild(textNode);
        return textNode;
    }
	
    private final String prettyPrint(Document xml) throws Exception {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
        tf.setOutputProperty(OutputKeys.INDENT, "yes"); 
        Writer out = new StringWriter();
        tf.transform(new DOMSource(xml), new StreamResult(out));
        return out.toString();
    }

}
Impressum - Datenschutzerklärung