我有一个包含XML的Java字符串,没有换行符或缩进.我想把它变成一个格式很好的XML的字符串.我该怎么做呢?
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
Run Code Online (Sandbox Code Playgroud)
注意:我的输入是一个字符串.我的输出是一个字符串.
(基本)模拟结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
Run Code Online (Sandbox Code Playgroud) 阅读java org.w3c.dom.ls的文档似乎只能将元素序列化为带有java本机字符串编码UTF-16的String.但是,我需要创建一个UTF-8字符串,转义或不存在,我知道它仍然是一个UTF-16字符串.任何人都有想法绕过这个?我需要将字符串传递给将使用String的生成的WS客户端,然后它应该是UTF-8.
我用来创建字符串的代码:
DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.
DOMImplementationLS domImplementationLS = (DOMImplementationLS) REGISTRY.getDOMImplementation("LS");
LSSerializer writer = domImplementationLS.createLSSerializer();
String result = writer.writeToString(element);
Run Code Online (Sandbox Code Playgroud) 我有一些使用嵌入式Scala生成的XML,但它并没有将生成的XML放在不同的行上.
目前,它看起来像这样,
<book id="0">
<author>Gambardella, Matthew</author><publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date><description>An in-depth loo
k at creating applications with XML.</description><price>44.95</price><genre>Computer</genre><title>XML Developer's Guide</title>
</book>
Run Code Online (Sandbox Code Playgroud)
但我希望它看起来像这样:
<book id="0">
<author>Gambardella, Matthew</author>
<publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date>
<description>An in-depth look at creating applications with XML.</description>
<price>44.95</price>
<genre>Computer</genre>
<title>XML Developer's Guide</title>
</book>
Run Code Online (Sandbox Code Playgroud)
如何控制格式?这是生成XML的代码
<book id="0">
{ keys map (_.toXML) }
</book>
Run Code Online (Sandbox Code Playgroud)
这是toXML:
def toXML:Node = XML.loadString(String.format("<%s>%s</%s>", tag, value.toString, tag))
Run Code Online (Sandbox Code Playgroud)