[英]Marshalling CDATA elements with CDATA_SECTION_ELEMENTS adds carriage return characters
[英]Transformer CDATA_SECTION_ELEMENTS modify my XML content
我有以下代码:
Transformer transformer1 = TransformerFactory.newInstance().newTransformer();
final DOMResult domResult = new DOMResult();
marshaller.marshal(objectForMarshall, domResult);
transformer1.setOutputProperty(OutputKeys.INDENT, "yes");
transformer1.setOutputProperty(
OutputKeys.CDATA_SECTION_ELEMENTS,
"Parameters");
transformer1.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer1.transform(new DOMSource(domResult.getNode()), new StreamResult(new FileOutputStream("D:\\1.xml")));
在objectForMarshall
有一个字节数组类型的字段。 我想放在CDATA
部分中的内容。
我有这个适配器:
public class CDATAAdapter extends XmlAdapter<String, byte[]> {
@Override
public String marshal(byte[] v) throws Exception {
return new String(v);
}
@Override
public byte[] unmarshal(String v) throws Exception {
return v.getBytes();
}
}
转换之后,在最终文件中,我得到CDATA中的内容,并用新行分隔:
<ConditionInstance ActionConditionComponent="Regular" Id="1026">
<Parameters><![CDATA[<regular_condition>
<union type="AND">
<operation allow_absent_property="false" type="BIGGER">
<left>
<Entity item="value" property="DateTo" type="datetime"/>
</left>
<right>
<Entity item="value" property="DateTo" type="datetime"/>
</right>
</operation>
</union>
</regular_condition>
]]></Parameters>
</ConditionInstance>
为什么会发生这种情况,我无法理解? 如何补救? 为什么转换器会更改我内容的内容?
如果我删除:
transformer1.setOutputProperty(
OutputKeys.CDATA_SECTION_ELEMENTS,
cDataTagName);
未添加新行!!!
<ConditionInstance ActionConditionComponent="Regular" Id="1026">
<Parameters><regular_condition>
<union type="AND">
<operation allow_absent_property="false" type="BIGGER">
<left>
<Entity item="value" property="DateTo" type="datetime"/>
</left>
<right>
<Entity item="value" property="DateTo" type="datetime"/>
</right>
</operation>
</union>
</regular_condition>
</Parameters>
</ConditionInstance>
我的猜测是Parameters元素的值是一个包含CRLF(x13 x10)字符对的字符串。
当您直接对其进行序列化时,CR被序列化为字符引用
,并且NL被序列化为实际的换行符。
当您将其序列化为CDATA部分的一部分时,CRLF被序列化为两个字符,x13,后跟x10; 并且无论您使用什么软件来显示输出,都将其显示为两行,而不是一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.