我感觉我要疯了。我想漂亮地打印一个没有模式的 org.w3c.dom.Document(在 Java 中)。缩进并不是我所需要的,我想要忽略无用的空行和空格。不知何故,这种情况不会发生,每次我从文件中解析 XML 或将其写回文件时,DOM 文档中都会有包含空格的文本节点(\n、空格等)。有没有一种方法可以让我简单地摆脱这些,无需架构,也无需通过迭代所有节点并删除空文本节点来自行转换 XML?
示例:我的输入文件如下所示(但有更多空行:)
<mytag>
<anothertag>content</anothertag>
</mytag>
我希望我的输出文件如下所示:
<mytag>
<anothertag>content</anothertag>
</mytag>
注意:我没有 XML 架构(因此我被迫调用 builder.setValidating(false)),并且运行此代码时我没有互联网连接。
谢谢!
更新:我发现了一些非常接近我需要的东西,也许它可以帮助其他士兵对抗没有架构的 XML 文档:
org.apache.axis.utils.XMLUtils.normalize(document);
源代码here 。在创建文档之后和使用 Transformer 编写文档之前调用此函数将产生漂亮的输出,并且完全不需要模式验证。 JB Nizet 也给了我一个可行的答案,但我感觉该代码的幕后正在进行一些验证,这将使其与我的用例不同。我将这个问题留待几天,以防有人有更好的解决方案。
最佳答案
这是一个工作示例:
public class Xml {
private static final String XML =
"<mytag>\n" +
" <anothertag>content</anothertag>\n" +
"\n" +
"\n" +
"\n" +
"</mytag>";
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(new StringReader(XML)));
NodeList childNodes = document.getDocumentElement().getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
System.out.println(childNodes.item(i));
}
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
System.out.println(writer.writeToString(document));
}
}
输出:
[#text:
]
[anothertag: null]
[#text:
]
<mytag>
<anothertag>content</anothertag>
</mytag>
因此,解析器不会验证,它会保留文本节点,并且序列化器生成的输出正如您所期望的那样。
关于java - 我想在没有模式的情况下漂亮地打印 org.w3c.dom.Document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951669/