Reputation: 119
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="<root><first>01</first><second>02</second></root>"/>
Upvotes: 1
Views: 107
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