原始问题
我正在尝试在没有任何外部库的情况下漂亮地打印 XML 文件,但无法让 Java 执行我想要的操作...这是到目前为止我的代码(我添加了类似问题的任何解决方案!):
TransformerFactory tfactory = TransformerFactory.newInstance();
tfactory.setAttribute("indent-number", 4);
Transformer transformer = tfactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
File file = new File("C:\\text.xml");
DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file));
transformer.transform(source, new StreamResult(file));
输入文件如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><root><test><item0>a</item0><item1>b</item1></test></root>
我收到如下输出:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<test>
<item0>a</item0>
<item1>b</item1>
</test>
</root>
现在我不明白的是为什么后面有一个空行<root>
和前面的缩进</test>
,但没有其他地方。在这个新文件上运行代码没有任何改变!
我希望我的输出文件如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<test>
<item0>a</item0>
<item1>b</item1>
</test>
</root>
Update
我从代码中删除了一些显然没有做任何事情的行:
TransformerFactory tfactory = TransformerFactory.newInstance();
tfactory.setAttribute("indent-number", 4);
Transformer transformer = tfactory.newTransformer();
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
File file = new File("C:\\text.xml");
DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file));
transformer.transform(source, new StreamResult(file));
现在,这会根据原始问题的单行文件创建一个漂亮的打印文件,以便回答该问题的一部分!我不知道到底是什么问题,但无论如何,现在可以了^^
但我也有一些由我的程序读取和写入的旧文件,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<test>
<item0>a</item0>
<item1>b</item1>
</test>
</root>
它们在每个节点后都有一个换行符,但没有缩进。我的代码使文件保持不变...我该如何纠正这个问题?