Java XML String to Document toDocument(String xml)

Here you can find the source of toDocument(String xml)

Description

to Document

License

Open Source License

Declaration

public static Document toDocument(String xml) throws Exception 

Method Source Code


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

import org.w3c.dom.Document;

import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.io.Reader;
import java.io.StringReader;

public class Main {
    public static Document toDocument(String xml) throws Exception {
        // default we ignore namespaces
        return toDocument(xml, false);
    }/*from w w  w  . j  av a 2  s.  c  om*/

    public static Document toDocument(String xml, boolean namespaceAware) throws Exception {
        return toDocument(xml, namespaceAware, false);
    }

    public static Document toDocument(String xml, boolean namespaceAware, boolean ignoreDtd) throws Exception {
        Reader input = new StringReader(xml);
        InputSource is = new InputSource(input);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(namespaceAware);

        // ignore dtd files
        if (ignoreDtd) {
            dbf.setValidating(false);
            dbf.setFeature("http://xml.org/sax/features/namespaces", false);
            dbf.setFeature("http://xml.org/sax/features/validation", false);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        }

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException exception) throws SAXException {
                throw exception;

            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        return db.parse(is);
    }
}

Related

  1. toDocument(String content)
  2. toDocument(String input)
  3. toDocument(String s)
  4. toDocument(String str)
  5. toDocument(String string)
  6. toDocument(String xml)
  7. toXmlDocument(final InputStream inputStream, final String path)
  8. toXMLDocument(String xmlString)
  9. writeDocumentToString(Document document)