1

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;"/>
4
  • what's wrong with the escape characters again? Commented Jan 12, 2015 at 17:54
  • It works. But if you have any control over the XML format, I strongly urge you to avoid this sort of thing. It's unreadable and hardly useful. Commented Jan 12, 2015 at 18:00
  • @SamIam I was expecting this: <ORGANIZATIONS xml="<root><first>01</first><second>02</second></root>"/> Commented Jan 12, 2015 at 18:05
  • @user2566397 that can make your xml invalid. It's much better to just unescape the xml when you parse it. Commented Jan 12, 2015 at 18:08

1 Answer 1

2

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.