Parsing XML from a String in Java
In Java, you can parse an XML document from a file using the DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile) method. However, what if you have XML data in a String and you want to parse it?
Solution:
To parse XML from a String, you can use the InputSource class. Here's a code snippet that shows how to do it:
<code class="java">import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringReader; public class ParseXMLFromString { public static Document loadXMLFromString(String xml) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); return builder.parse(is); } }</code>
Simply pass the XML data as a string to the loadXMLFromString() function to parse it and extract the XML document object.
Related Question:
Check out this similar question for further insights into parsing XML from a string:
The above is the detailed content of How to Parse XML from a String in Java?. For more information, please follow other related articles on the PHP Chinese website!