tags:

views:

26

answers:

1

Hi. Can I print an XML document using escaped text instead of CDATA sections? For example, I want the output string as &lt;sender&gt;John Smith&lt;/sender&gt; instead of <![CDATA[<sender>John Smith</sender>]]>. UPDATE: I know an XML document can be represented in both ways without any sematic difference, but I want to print the output string on screen.

Here is my code:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
StringWriter streamWriter = new StringWriter();
StreamResult streamResult = new StreamResult(streamWriter);
DOMSource source = new DOMSource(xml);
transformer.transform(source, streamResult);
return streamWriter.toString();

And here is the output:

<?xml version="1.0" encoding="UTF-8"?>
<VNET>
  <ID>1</ID>
  <UID>0</UID>
  <NAME>ranged</NAME>
  <TYPE>0</TYPE>
  <BRIDGE>virbr0</BRIDGE>
  <PUBLIC>1</PUBLIC>
  <TEMPLATE>
    <BRIDGE><![CDATA[virbr0]]></BRIDGE>
    <NAME><![CDATA[ranged]]></NAME>
    <NETWORK_ADDRESS><![CDATA[192.168.0.0]]></NETWORK_ADDRESS>
    <NETWORK_SIZE><![CDATA[c]]></NETWORK_SIZE>
    <TYPE><![CDATA[ranged]]></TYPE>
  </TEMPLATE>
  <LEASES/>
</VNET>

Thanks a lot.

A: 

Both XMLs (CDATA and with &gt; etc.) are equivalent. An XML parser will read the character data in the same way and produce the same string. So it doesn't matter which is used; just leave it however the XML generator does it.

Adrian Smith
Thanks for answering. I know an XML document can be represented in both ways without any sematic difference, but I want to print the output string on screen.
Hai Minh Nguyen