我正在使用Java的内置XML转换器来获取DOM文档并打印出生成的XML.问题是尽管明确地设置了参数"indent",但它根本没有缩进文本.
示例代码
public class TestXML {
public static void main(String args[]) throws Exception {
ByteArrayOutputStream s;
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
Element a,b;
a = d.createElement("a");
b = d.createElement("b");
a.appendChild(b);
d.appendChild(a);
t.setParameter(OutputKeys.INDENT, "yes");
s = new ByteArrayOutputStream();
t.transform(new DOMSource(d),new StreamResult(s));
System.out.println(new String(s.toByteArray()));
}
}
Run Code Online (Sandbox Code Playgroud)
结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b/></a>
Run Code Online (Sandbox Code Playgroud)
期望的结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
<b/>
</a>
Run Code Online (Sandbox Code Playgroud)
思考?
使用以下简单代码:
package test;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class TestOutputKeys {
public static void main(String[] args) throws TransformerException {
// Instantiate transformer input
Source xmlInput = new StreamSource(new StringReader(
"<!-- Document comment --><aaa><bbb/><ccc/></aaa>"));
StreamResult xmlOutput = new StreamResult(new StringWriter());
// Configure transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(); // An identity transformer
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
System.out.println(xmlOutput.getWriter().toString());
}
}
Run Code Online (Sandbox Code Playgroud)
我得到输出:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Document comment --><!DOCTYPE aaa SYSTEM "testing.dtd">
<aaa>
<bbb/>
<ccc/>
</aaa>
Run Code Online (Sandbox Code Playgroud)
问题A:doctype标签出现在文档注释之后.是否有可能在文件评论之前出现?
问题B:如何仅使用JavaSE 5.0 …
我正在编写一个包含以下代码的XML文件:
Source source = new DOMSource(rootElement);
Result result = new StreamResult(xmlFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
Run Code Online (Sandbox Code Playgroud)
这是输出文件:
<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
<sequence>
<initial-frame>0</initial-frame>
<points>
<point>
<x>274.0</x>
<y>316.0</y>
</point>
...
Run Code Online (Sandbox Code Playgroud)
我希望这个文件缩进,例如:
<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
<sequence>
<initial-frame>0</initial-frame>
<points>
<point>
<x>274.0</x>
<y>316.0</y>
</point>
...
Run Code Online (Sandbox Code Playgroud)
setOutputProperty在我的代码中调用并没有解决问题,它实际上使文本用新行(但不缩进).
任何人都有解决方案,而不需要外部库?