java生成xml文件换行_如何在生成XML时保留CDATA中的换行符?

Aviad Ben Do..

5

我不知道你如何解析和编写你的文档,但这是一个基于你的增强代码示例:

// creating the document in-memory

Document xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

Element element = xmldoc.createElement("TestElement");

xmldoc.appendChild(element);

element.appendChild(xmldoc.createCDATASection("first line\nsecond line\n"));

// serializing the xml to a string

DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

DOMImplementationLS impl =

(DOMImplementationLS)registry.getDOMImplementation("LS");

LSSerializer writer = impl.createLSSerializer();

String str = writer.writeToString(xmldoc);

// printing the xml for verification of whitespace in cdata

System.out.println("--- XML ---");

System.out.println(str);

// de-serializing the xml from the string

final Charset charset = Charset.forName("utf-16");

final ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes(charset));

Document xmldoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

Node vs = xmldoc2.getElementsByTagName("TestElement").item(0);

final Node child = vs.getFirstChild();

String x = child.getNodeValue();

// print the value, yay!

System.out.println("--- Node Text ---");

System.out.println(x);

使用LSSerializer进行序列化是W3C的方法(参见此处).输出是预期的,带有行分隔符:

--- XML ---

second line ]]>

--- Node Text ---

first line

second line

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值