Here you can find the source of stringToElement(String xml)
Parameter | Description |
---|---|
xml | snippet as a string |
Parameter | Description |
---|---|
Exception | if unable to parse the String or if it doesn't contain valid XML. |
public static Element stringToElement(String xml) throws Exception
//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(); } }