Convert String to XML and XML to String in Java

While writing an automation test script, you may encounter situations where you need to convert a string to an XML document and an XML document to a string in Java.In this article, we will learn the following things that will ease your work.

  • Convert a String to XML Document Object in Java
  • Convert an XML document object to String in Java
  • Read an XML File and Convert it to XML Doc in Java

Convert String to XML document and XML to String in Java

The conversion of String to XML Document or vice versa is often required if you work on Web Services ( Soap Request ) automation.

Java Code to Convert String to XML Document

To convert the String to XML document, we will use DocumentBuilderFactory and DocumentBuilder classes.

Java Code to Convert an XML Document to String

In the previous example we saw how to convert a String to XML document.The following example first converts a String to XML document and then converts it back to String.For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes.

Read an XML File and Convert it to XML Document in Java

Sometimes we need to read an XML file and perform various operations on it. The following java program shows us how to read an XML file and convert it to an XML document.

Conclusion

We have learned how to convert String to an XML and an XML to String in Java.Also,we have seen way to convert XML file to XML document.I hope you would like this article.Please don’t forget to share it.

Recommended Posts

Leave a Reply