开发者

In Java, how to print an XML document using escaped text instead of CDATA sections?

开发者 https://www.devze.com 2023-01-21 23:58 出处:网络
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[<se

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号