Java XML Element from String stringToElement(String xml)

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

Description

Converts a String representing an XML snippet into an org.w3c.dom.Element .

License

Apache License

Parameter

Parameter Description
xml snippet as a string

Exception

Parameter Description
Exception if unable to parse the String or if it doesn't contain valid XML.

Return

a DOM Element

Declaration

public static Element stringToElement(String xml) throws Exception 

Method Source Code


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

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

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

import java.io.ByteArrayInputStream;

public class Main {
    /**//from  w  ww.  ja v a2  s  .c  o  m
     * Converts a String representing an XML snippet into an {@link org.w3c.dom.Element}.
     *
     * @param xml snippet as a string
     * @return a DOM Element
     * @throws Exception if unable to parse the String or if it doesn't contain valid XML.
     */
    public static Element stringToElement(String xml) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf8"));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document d = builder.parse(bais);
        bais.close();
        return d.getDocumentElement();
    }
}

Related

  1. stringToElement(final String inputXml)
  2. stringToElement(String s)