使用带有CDATA部分的Transformer的Java格式xml [英] Java format xml using Transformer with CDATA part

查看:219
本文介绍了使用带有CDATA部分的Transformer的Java格式xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Source xmlInput = new StreamSource(new StringReader(input)) ; 
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
变压器变压器= transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,yes);
transformer.setOutputProperty({http://xml.apache.org/xslt}indent-amount,String.valueOf(4));
transformer.transform(xmlInput,xmlOutput);

这是我的字符串

 < a>< attr name =a1>这是一个测试< / attr>< attr name =a2><![CDATA [ cdata部分]]>< / attr>< / a> 

输出

 <?xml version =1.0encoding =UTF-8?> 
< a>
< attr name =a1>这是一个测试< / attr>
< attr name =a2><![CDATA [这是cdata部分内的测试]]< / attr>
< / a>

期望

 <?xml version =1.0encoding =UTF-8?> 
< a>
< attr name =a1>
这是一个测试
< / attr>
< attr name =a2>
<![CDATA [这是cdata部分的测试]]>
< / attr>
< / a>

我希望每个新标签都以新行开始。



顺便说一句,在规范中也没有定义CDATA将保留在JAXP标识转换中,我对这种情况有些惊讶。

I want to format string to xml this my code:

Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(4));
transformer.transform(xmlInput, xmlOutput);

This is my String

 <a><attr name="a1">this is a test</attr><attr name="a2"><![CDATA[this is a test inside cdata part]]></attr></a>

Output

<?xml version="1.0" encoding="UTF-8"?>
<a>
    <attr name="a1">this is a test</attr>
    <attr name="a2"><![CDATA[this is a test inside cdata part]]></attr>
</a>

desired

<?xml version="1.0" encoding="UTF-8"?>
<a>
    <attr name="a1">
        this is a test
    </attr>
    <attr name="a2">
        <![CDATA[this is a test inside cdata part]]>
    </attr>
</a>

I want each new tag will start in new line.

解决方案

The precise effect of OutputKeys.INDENT is not defined in the specifications. The XSLT 2.0 version of the spec, however, is explicit that indentation must add whitespace only before a start tag or after an end tag - in other words, the value of a non-whitespace text node will never be changed.

Incidentally, it's also not defined in the spec that CDATA will be preserved in a JAXP identity transformation, and I'm slightly surprised that this happens.

这篇关于使用带有CDATA部分的Transformer的Java格式xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆