Java parse string to xml dom
Here is an example of how to parse a string containing XML to a DOM object in Java using the standard Java libraries:
String xmlString = "<root><element>value</element></root>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource inputSource = new InputSource(new StringReader(xmlString)); Document document = builder.parse(inputSource); Element rootElement = document.getDocumentElement();Source:wwitfigi.wdea.com
In this example, we create a String
object containing the XML to be parsed. We then create a DocumentBuilderFactory
object and use it to create a DocumentBuilder
. The DocumentBuilder
is used to parse the InputSource
object created from the String
object. Finally, we obtain the root element of the resulting Document
object.
Note that this code may throw exceptions such as ParserConfigurationException
, SAXException
, and IOException
, so you should be prepared to handle these exceptions in your code.