Create new Document and set version and encoding - Java XML

Java examples for XML:DOM Document

Description

Create new Document and set version and encoding

Demo Code


//package com.java2s;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {
    public final static Document newDocument(String rootName)
            throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document xml = db.newDocument();
        Node root = xml.createElement(rootName);
        Attr a = xml.createAttribute("version");
        a.setValue("0.6");
        root.getAttributes().setNamedItem(a);

        a = xml.createAttribute("encoding");
        a.setValue("UTF-8");
        root.getAttributes().setNamedItem(a);
        xml.appendChild(root);/*from w  w w  . j  av a2s  . com*/
        return xml;
    }
}

Related Tutorials