Convert an XML Object to a String in Java

1. Introduction

XML (eXtensible Markup Language) is one of the most popular schemas for structuring information. Moreover, the parsing and manipulation of XML Documents in Java are commonly accomplished using technologies like DOM (Document Object Model) and SAX (Simple API for XML).

In some cases, it might be necessary to transform an XML Document object into its string form, which could be used to store the XML information inside a database or to pass through over a network.

In this tutorial, we’ll discuss several ways of transforming an XML Document object into a string in Java.

2. Example

Suppose we have the following Document object:

Document document = // ...

This Document object represents XML content in memory:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <child1>This is child element 1</child1>
    <child2>This is child element 2</child2>
</root>

Now, we need to convert this XML Document object into a Java string.

3. Using XML Transformation APIs

The javax.xml.transform package in Java includes classes and interfaces for performing XML transformations. One of its capabilities is the conversion of an XML Document object into a string representation. The following code demonstrates how to use the javax.xml.transform package to parse this XML Document object to a Java string:

@Test
public void givenXMLDocument_whenUsingTransformer_thenConvertXMLToString()
throws TransformerException {  
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    String result = stringWriter.toString();
    assertTrue(result.contains("<root>"));
    assertTrue(result.contains("This is child element 1"));
    assertTrue(result.contains("This is child element 2"));
}

We first instantiate a TransformerFactory and a Transformer, used for XML transformation. Then, we construct a StringWriter to store the transformed XML in text form. Then, the transform() method changes the XML Document, and we can save it into the result string using the stringWrite.toString() method.

4. Using Java XMLBeans

Converting between XML Document and string is easy and flexible using the XmlBeans approach in the Java XML manipulation world. We use XmlObject.Factory.parse(document), which parses the XML Document into an XmlObject for subsequent operative activities:

@Test
public void givenXMLDocument_whenUsingXmlBeans_thenConvertXMLToString() {
    try {
        XmlObject xmlObject = XmlObject.Factory.parse(document);
        XmlOptions options = new XmlOptions();
        options.setSavePrettyPrint();
        options.setUseDefaultNamespace();
        options.setSaveAggressiveNamespaces();
        String xmlString = xmlObject.xmlText(options);
        xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + xmlString;
        assertTrue(xmlString.contains("<root>"));
        assertTrue(xmlString.contains("This is child element 1"));
        assertTrue(xmlString.contains("This is child element 2"));
    } catch (XmlException e) {
        e.printStackTrace();
    }
}

In the above test method, we parse the document into an XmlObject using XmlOptions to customize output formatting such as pretty-printing, namespaces, etc. Moreover, asserts are done to establish that a resulting XML string contains an XML declaration and particular XML elements and element contents.

5. Conclusion

In this tutorial, we discuss how to convert an XML Document object to a string in Java.

As always, the complete code samples for this article can be found over on GitHub.

       

Commercials Cooperation Advertisements:


(1) IT Teacher IT Freelance

IT電腦補習

立刻註冊及報名電腦補習課程吧!
电子计算机 -教育 -IT 電腦班” ( IT電腦補習 ) 提供一個方便的电子计算机 教育平台, 為大家配對信息技术, 電腦 老師, IT freelance 和 programming expert. 讓大家方便地就能找到合適的電腦補習, 電腦班, 家教, 私人老師.
We are a education and information platform which you can find a IT private tutorial teacher or freelance.
Also we provide different information about information technology, Computer, programming, mobile, Android, apple, game, movie, anime, animation…


(2) ITSec

https://itsec.vip/

www.ITSec.vip

www.Sraa.com.hk

www.ITSec.hk

www.Penetrationtest.hk

www.ITSeceu.uk

Secure Your Computers from Cyber Threats and mitigate risks with professional services to defend Hackers.

ITSec provide IT Security and Compliance Services, including IT Compliance Services, Risk Assessment, IT Audit, Security Assessment and Audit, ISO 27001 Consulting and Certification, GDPR Compliance Services, Privacy Impact Assessment (PIA), Penetration test, Ethical Hacking, Vulnerabilities scan, IT Consulting, Data Privacy Consulting, Data Protection Services, Information Security Consulting, Cyber Security Consulting, Network Security Audit, Security Awareness Training.

Contact us right away.

Email (Prefer using email to contact us):
SalesExecutive@ITSec.vip

Leave a Reply

Your email address will not be published. Required fields are marked *