Java XML Document Create newDocument()

Here you can find the source of newDocument()

Description

new Document

License

Open Source License

Declaration

public static Document newDocument() 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

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

public class Main {

    public static Document newDocument() {
        try {/*from  w w  w .j a v  a2 s .c om*/
            DocumentBuilder builder = createDefaultDocumentBuilderFactory().newDocumentBuilder();
            return builder.newDocument();
        } catch (ParserConfigurationException e) {
            //not occur
            e.printStackTrace();
            throw new IllegalStateException(e);
        }
    }

    public static Document newDocument(String nsuri, String qname) {
        Document doc = newDocument();
        Element el = doc.createElementNS(nsuri, qname);
        if (nsuri != null) {
            int idx = qname.indexOf(':');
            if (idx == -1) {
                el.setAttribute("xmlns", nsuri);
            } else {
                el.setAttribute("xmlns:" + qname.substring(0, idx), nsuri);
            }
        }
        doc.appendChild(el);
        return doc;
    }

    public static DocumentBuilder newDocumentBuilder(boolean ignoreWhitespace, boolean ignoreComment) {
        try {
            DocumentBuilderFactory dbf = createDefaultDocumentBuilderFactory();
            dbf.setIgnoringElementContentWhitespace(ignoreWhitespace);
            dbf.setIgnoringComments(ignoreComment);
            return dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            //not occur
            e.printStackTrace();
            throw new IllegalStateException(e);
        }
    }

    public static final DocumentBuilderFactory createDefaultDocumentBuilderFactory() {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setCoalescing(true);
        dbf.setExpandEntityReferences(true);
        dbf.setIgnoringComments(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        dbf.setXIncludeAware(true);
        return dbf;
    }
}

Related

  1. newDocument()
  2. newDocument()
  3. newDocument()
  4. newDocument()
  5. newDocument()
  6. newDocument()
  7. newDocument()
  8. newDocument()
  9. newDocument()