原始问题
我想在没有任何外部库的情况下对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>
更新
我已经从我的代码中删除了一些明显没有起到任何作用的行:
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>
每个节点之后都有一个换行符,但没有缩进。我的代码保留了文件的原样... 我该如何更正?
tfactory
的类是什么?您使用的JDK是什么? - werotfactory
的实现类是什么?即,当您打印System.out.println(tfactory.getClass())
时。 - wero