user2566397
user2566397

Reputation: 119

Store xml into xml attribute

How can I store a xml document into xml attribute? I have this code but de output give me escape characters, is right left with these escape characters?

public static void main(String[] args) throws TransformerException,
    ParserConfigurationException  {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element organizations = doc.createElement("ORGANIZATIONS");
        doc.appendChild(organizations);
        organizations.setAttribute("xml", "<root><first>01</first><second>02</second></root>");
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        StreamResult sr = new StreamResult(new File("test.xml"));

        transformer.transform(domSource, sr);

    }

output:

<ORGANIZATIONS xml="&lt;root&gt;&lt;first&gt;01&lt;/first&gt;&lt;second&gt;02&lt;/second&gt;&lt;/root&gt;"/>

Upvotes: 1

Views: 107

Answers (1)

Nicola Ferraro
Nicola Ferraro

Reputation: 4179

This is correct. The xml should be escaped when set on an attribute. If you want to see the plain xml, you have to put it on an element and force the usage of CDATA sections for it:

transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "thequalifiednameoftheelement");

CDATA sections cannot be used on attributes... Attributes are not made for being filled with xml documents...

Upvotes: 2

Related Questions