Java XML Element from String stringToElement(final String inputXml)

Here you can find the source of stringToElement(final String inputXml)

Description

Convert XML string to Element.

License

Open Source License

Parameter

Parameter Description
inputXml XML string.

Return

Element

Declaration

public static Element stringToElement(final String inputXml)
        throws IOException 

Method Source Code

//package com.java2s;
/**************************************************************************
 * Copyright (c) 2015, Toshiki Iga, All rights reserved.
 * /*from   ww  w.j a v a  2 s . c  o m*/
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 * If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************** */

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

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 {
    /**
     * Convert XML string to Element.
     * 
     * @param inputXml
     *            XML string.
     * @return Element
     */
    public static Element stringToElement(final String inputXml)
            throws IOException {
        try {
            final DocumentBuilder builder = DocumentBuilderFactory
                    .newInstance().newDocumentBuilder();
            final Document document = builder
                    .parse(new ByteArrayInputStream(inputXml
                            .getBytes("UTF-8")));
            return document.getDocumentElement();
        } catch (ParserConfigurationException ex) {
            throw new IOException(
                    "IgapyonXmlUtil#stringToElement: Fail to configure xml parser: ",
                    ex);
        } catch (SAXException ex) {
            throw new IOException(
                    "IgapyonXmlUtil#stringToElement: Fail to process xml: ",
                    ex);
        }
    }
}

Related

  1. stringToElement(String s)
  2. stringToElement(String xml)