Java XML String Transform String2Doc(String InputXMLString)

Here you can find the source of String2Doc(String InputXMLString)

Description

Helper program: Transforms a String to a XML Document.

License

Apache License

Parameter

Parameter Description
InputXMLString the input xml string

Exception

Parameter Description

Return

parsed document

Declaration

public static Document String2Doc(String InputXMLString) 

Method Source Code


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

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.StringReader;

public class Main {
    /**/*  w ww .ja  v  a 2  s  .c om*/
     * Helper program: Transforms a String to a XML Document.
     *
     * @param InputXMLString the input xml string
     * @return parsed document
     * @throws javax.xml.parsers.ParserConfigurationException the parser configuration exception
     * @throws java.io.IOException                            Signals that an I/O exception has occurred.
     */
    public static Document String2Doc(String InputXMLString) {
        try {
            DocumentBuilder builder = getDocumentBuilder();
            InputSource is = new InputSource(new StringReader(InputXMLString));
            is.setEncoding("UTF-8");
            return builder.parse(is);
        } catch (Exception e) {
            System.out.println("cannot parse following content\\n\\n" + InputXMLString);
            e.printStackTrace();
            return null;
        }
    }

    private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        // Unfortunately we can not ignore whitespaces without a schema.
        // So we use the NdLst workaround for now.
        domFactory.setAttribute("http://apache.org/xml/features/dom/include-ignorable-whitespace", Boolean.FALSE);
        return domFactory.newDocumentBuilder();
    }
}

Related

  1. readXMLFile(String xmlFileName)
  2. render(String name, byte[] xmldata)
  3. replaceLineSeparatorInternal(String string, String lineSeparator)
  4. save(Node doc, OutputStream stream, String encoding, boolean indent)
  5. signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert)
  6. string2Source(String xml)
  7. stringToNode(String s)
  8. strToSchema(final String strXsd)
  9. toElement(String xml)