Home > Java > javaTutorial > How to Parse XML from a String in Java?

How to Parse XML from a String in Java?

Patricia Arquette
Release: 2024-11-06 07:34:02
Original
715 people have browsed it

How to Parse XML from a String in Java?

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>
Copy after login

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:

  • [How to parse XML from a string using Java?](https://stackoverflow.com/questions/1070821/how-to-parse-xml-from-a-string-using-java)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template