Java XML Document Create stringToDocument(String doc)

Here you can find the source of stringToDocument(String doc)

Description

Simple method to parse a string into a w3c Document

License

Apache License

Parameter

Parameter Description
doc the string to parse

Exception

Parameter Description
SAXException if the string did not contain valid html.

Return

the document

Declaration

public static Document stringToDocument(String doc) throws SAXException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**/*from ww w . j a v  a  2  s. co m*/
     * Simple method to parse a string into a w3c Document
     * @param doc the string to parse
     * @return the document
     * @throws SAXException if the string did not contain valid html.
     */
    public static Document stringToDocument(String doc) throws SAXException {
        InputStream in = new ByteArrayInputStream(doc.getBytes());
        try {
            return getDOCUMENT_BUILDER().parse(in);
        } catch (IOException e) {
            throw new Error("Problem reading a string, should never happen", e);
        }
    }

    public static DocumentBuilder getDOCUMENT_BUILDER() {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            return documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new Error("Error initialising default document builder", e);
        }
    }
}

Related

  1. newXmlDocument()
  2. newXmlDocument()
  3. string2Document(final String xml)
  4. string2Document(String xml, String encode)
  5. stringToDocument(final String xml)
  6. stringToDocument(String string)
  7. stringToDocument(String string)
  8. stringToDocument(String string)
  9. stringToDocument(String xml)