Friday, March 22, 2019

XML Java Transformer outputs instead of <>

I share example how java Transformer outputs &lt; and &gt; instead of <> on XML.

/**
Example
*/

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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Test {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
            "&lt;company&gt;" +
            "&lt;staff id=\"1001\"&gt;" +
            "&lt;firstname&gt;henry&lt;/firstname&gt;" +
            "&lt;/staff&gt;" +
            "&lt;/company&gt;";



        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(StringEscapeUtils.unescapeXml(xml.toString()))));

        System.out.println("final xml " + xmlTransformerInput(doc).toString());

    }


    public static String xmlTransformerInput(Document fDoc) {

        try {

            fDoc.setXmlStandalone(true);
            DOMSource docSource = new DOMSource(fDoc);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            transformer.transform(docSource, new StreamResult(sw));

            return sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}

No comments:

Post a Comment

Virtual Threads in Java 21: Simplified Concurrency for Modern Applications

  With Java 21, Virtual Threads have redefined how we approach concurrency, offering a lightweight and efficient way to handle parallel and ...