- Java Convert String to XML DOM Example
- 5 Ways to Convert String to XML in Java: A Complete Guide
- Using DocumentBuilder and DocumentBuilderFactory
- Using JDOM library
- Converting JSON to XML using org.json.XML
- Utility methods
- Additional tips and best practices
- Other code samples that can quickly convert string to XML in Java
- Conclusion
- Java Convert String to XML Document and XML Document to String
- Java XML Formatter With Examples [Latest]
- Java XML Formatter
Java Convert String to XML DOM Example
To convert XML string to XML Dom, we need the following classes:
- javax.xml.parsers.DocumentBuilder : Defines the API to obtain XML DOM Document instances from XML content from various input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
- javax.xml.parsers.DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser ( DocumentBuilder ) that produces DOM object trees from XML content.
- org.w3c.dom.Document : It represents the entire XML DOM. Conceptually, it is the root of the document tree, and provides the access to the document’s data further down into the tree, through factory methods.
- java.io.StringReader : Create a stream from String content. DocumentBuilder uses this stream to read XML content for parsing.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class ConvertStringToXML < public static void main(String[] args) < final String xmlStr + " Lokesh Gupta" + " " + " " + " Brian Lara" + " " + " " + ""; //Use method to convert XML string content to XML Document object Document doc = convertStringToXMLDocument(xmlStr); //Verify XML document is build correctly System.out.println("Root Node : " + doc.getFirstChild().getNodeName()); NodeList nodeList = doc.getElementsByTagName("employee"); for (int itr = 0; itr < nodeList.getLength(); itr++) < Node node = nodeList.item(itr); System.out.println("\nNode Name : " + node.getNodeName()); if (node.getNodeType() == Node.ELEMENT_NODE) < Element eElement = (Element) node; System.out.println("Name: "+ eElement.getElementsByTagName("name").item(0).getTextContent()); System.out.println("Title: "+ eElement.getElementsByTagName("title").item(0).getTextContent()); >> > private static Document convertStringToXMLDocument(String xmlString) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new InputSource(new StringReader(xmlString))); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
Root Node : employees Node Name : employee Name: Lokesh Gupta Title: Author Node Name : employee Name: Brian Lara Title: Cricketer
2. Convert XML File to XML Document
To get the XML dom from XML file, instead of passing the XML string to DocumentBuilder, pass the file path to let the parser read the file content directly.
We have employees.xml file which has XML content, we will read to get XML document.
Lokesh Gupta Brian Lara
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class StringtoXMLExample < public static void main(String[] args) < final String xmlFilePath = "employees.xml"; //Use method to convert XML string content to XML Document object Document doc = convertXMLFileToXMLDocument( xmlFilePath ); //Verify XML document is build correctly System.out.println(doc.getFirstChild().getNodeName()); >private static Document convertXMLFileToXMLDocument(String filePath) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new File(filePath)); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
Drop me your questions in the comments section.
5 Ways to Convert String to XML in Java: A Complete Guide
Learn the different methods to convert a string to an XML file in Java. Follow best practices, including standard XML schema rules, and choose between the DocumentBuilder, JDOM library, and org.json.XML class. Discover the utility methods available to convert an XML document to a string and vice versa. Get started now!
Java is a widely used programming language that provides developers with various options for parsing and manipulating data, including the ability to convert a string to an XML file. In this blog post, we will explore the different methods to convert a string to an XML file in Java.
Using DocumentBuilder and DocumentBuilderFactory
The DocumentBuilder and DocumentBuilderFactory classes can be used to parse a string into an XML Document object. This method is efficient and widely used by Java developers.
To use this method, we first need to create an instance of DocumentBuilderFactory by calling the newInstance() method. We then create an instance of DocumentBuilder using the newDocumentBuilder() method. Finally, we create an InputSource object from the string we want to convert to an XML file and parse it using the parse() method on the DocumentBuilder object. Here’s an example:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xmlString)); Document doc = builder.parse(is);
The resulting doc object can be navigated using DOM or JDOM2 parsers.
Using JDOM library
The JDOM library is an open-source, Java-based library optimized for Java developers to parse XML documents. This library is more user-friendly than using DOM or SAX parser directly.
To use the JDOM library, we need to create an instance of SAXBuilder and use the build() method to parse the string into an XML Document object. Here’s an example:
SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(new StringReader(xmlString));
Converting JSON to XML using org.json.XML
The org.json.XML class can be used to convert JSON objects into an XML string. This can be useful when working with JSON data that needs to be converted to an XML format.
To use this method, we first need to create a JSONObject object from the JSON string we want to convert. We can then use the toString() method on the XML object to convert the JSON object to an XML string. Here’s an example:
JSONObject json = new JSONObject(jsonString); String xml = XML.toString(json);
It’s important to properly escape special characters to avoid any issues when converting.
Utility methods
Java also provides utility methods to convert an XML Document object to a string and vice versa. This can be useful when we want to convert an XML string to a Document object, or vice versa.
To convert an XML Document object to a string, we can use the toString() method on the XML object. To convert a string to an XML Document object, we can use the toJSONObject() method on the XML object. Here’s an example:
String xmlString = XML.toString(doc); Document doc = XML.toJSONObject(xmlString);
The JAXB API can also be used to convert an XML document to a string and vice versa.
Additional tips and best practices
When converting a string to an XML file, it’s important to follow standard XML schema rules. This can help prevent any issues when parsing the XML document.
Common issues include errors in the XML schema and issues with parsing the XML document. Java provides many options for writing XML files, including the use of the Transformer class and the FileWriter class.
Developers can benefit from knowing the differences between DOM and SAX parsers for parsing XML documents. DOM parsers create an in-memory representation of the entire XML document, while SAX parsers read the XML document sequentially and do not store the entire document in memory.
Consider using an XML editor or IDE for working with XML files. This can help with syntax highlighting, code completion, and other useful features.
Other code samples that can quickly convert string to XML in Java
In Java , in particular, string to xml in java code example
String xml = "\n" + "-2 \n" + "\n" + "100 \n" + "ERROR HERE. \n" + " \n" + " "; Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(xml)));NodeList errNodes = doc.getElementsByTagName("error"); if (errNodes.getLength() > 0) < Element err = (Element)errNodes.item(0); System.out.println(err.getElementsByTagName("errorMessage") .item(0) .getTextContent()); >else < // success >
In Java , for example, xml string to java object code example
Conclusion
In conclusion, Java provides various classes and methods to convert a string to an XML file. The DocumentBuilder and DocumentBuilderFactory classes, JDOM library, and org.json.XML class are all viable options. Utility methods are available to convert an XML Document object to a string and vice versa. Best practices include following standard XML schema rules and knowing the differences between DOM and SAX parsers. By following these methods and best practices, developers can effectively convert a string to an XML file in Java.
Java Convert String to XML Document and XML Document to String
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
- Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.
- String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String. We will use Transformer , StringWriter and StreamResult for this purpose.
package com.journaldev.xml; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class StringToDocumentToString < public static void main(String[] args) < final String xmlStr = "\n"+ "DeveloperMale "; Document doc = convertStringToDocument(xmlStr); String str = convertDocumentToString(doc); System.out.println(str); > private static String convertDocumentToString(Document doc) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); // below code to remove XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; >catch (TransformerException e) < e.printStackTrace(); >return null; > private static Document convertStringToDocument(String xmlStr) < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try < builder = factory.newDocumentBuilder(); Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
When we run above program, we get the same String output that we used to create DOM Document.
You can use replaceAll("\n|\r", "") to remove new line characters from String and get it in compact format.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java XML Formatter With Examples [Latest]
eXtensive Markup Language (XML) is one of the popular medium for messaging and communication between different applications. Since XML is open source and provides control over data format via DTD and XSDs, it’s widely used across technologies.
Java XML Formatter
Few days back, I came across a situation where the third party API was returning Document object and XML message as String. So I wrote this simple XmlFormatter class to format the XML with proper indentation and convert Document object to XML String.
String book = «<?xml version crayon-cn»>1.0 «?><catalog><book id crayon-i»>bk101 «><author>Gambardella, Matthew</author><title>XML Developers Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book><book id crayon-i»>bk102 «><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date><description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description></book></catalog>» ;
To use this class, you need Apache xercesImpl.jar that you can download from their website.
Output of the above class is a properly formatted XML String: