Java XML Element Root getRootFromString(String str)

Here you can find the source of getRootFromString(String str)

Description

get Root From String

License

Apache License

Declaration

public static Element getRootFromString(String str)
            throws SAXException, IOException, ParserConfigurationException 

Method Source Code

//package com.java2s;
/*//  ww w.j  a va  2  s.  c o  m
 *  Copyright 2009 Peter Karich, peat_hal ?at? users ?dot? sourceforge ?dot? net.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

import java.io.ByteArrayInputStream;

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

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

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

import org.xml.sax.SAXException;

public class Main {
    public static Element getRootFromString(String str)
            throws SAXException, IOException, ParserConfigurationException {
        return getAsDocument(str).getDocumentElement();
    }

    public static Document getAsDocument(String xmlString)
            throws SAXException, IOException, ParserConfigurationException {
        return newDocumentBuilder().parse(new ByteArrayInputStream(xmlString.getBytes()));
    }

    public static Document parse(InputStream is) throws SAXException, IOException, ParserConfigurationException {
        return newDocumentBuilder().parse(is);
    }

    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);
        DocumentBuilder builder = factory.newDocumentBuilder();

        return builder;
    }
}

Related

  1. getRootElementFromString(String payload)
  2. getRootElementName(Class clazz)
  3. getRootElementPosition(String buf, Element root)
  4. getRootFaceletElement(Document document)
  5. getRootFromPom(File pomFile)
  6. getRootNode(Document doc, String nodeName)
  7. getRootNode(Document document)
  8. getRootNode(final String xmlContent)
  9. getRootTagName(String xml)