58

使用以下简单代码:

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());
    }

}

我得到输出:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Document comment --><!DOCTYPE aaa SYSTEM "testing.dtd">

<aaa>
<bbb/>
<ccc/>
</aaa>

问题 A:doctype 标签出现在文档注释之后。是否可以让它出现在文档注释之前?

问题 B:如何实现缩进,仅使用 JavaSE 5.0 API?这个问题本质上与How to pretty-print xml from java相同,但是该问题中的几乎所有答案都取决于外部库。仅使用 java api 的唯一适用答案(由名为 Lorenzo Boccaccia 的用户发布)基本上等于上面发布的代码,但对我不起作用(如输出所示,我没有缩进)。

我猜你必须设置用于缩进的空格数量,就像外部库的许多答案一样,但我只是找不到在 java api 中指定的位置。鉴于在 java api 中存在将缩进属性设置为“是”的可能性,因此必须能够以某种方式执行缩进。我只是不知道怎么做。

4

4 回答 4

118

缺少的部分是缩进量。您可以设置缩进和缩进量如下:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
于 2009-08-12T08:11:37.190 回答
5

一个小工具类作为例子......

import org.apache.xml.serialize.XMLSerializer;

public class XmlUtil {

public static Document file2Document(File file) throws Exception {
    if (file == null || !file.exists()) {
        throw new IllegalArgumentException("File must exist![" + file == null ? "NULL"
                : ("Could not be found: " + file.getAbsolutePath()) + "]");
    }
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    return dbFactory.newDocumentBuilder().parse(new FileInputStream(file));
}

public static Document string2Document(String xml) throws Exception {
    InputSource src = new InputSource(new StringReader(xml));
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    return dbFactory.newDocumentBuilder().parse(src);
}

public static OutputFormat getPrettyPrintFormat() {
    OutputFormat format = new OutputFormat();
    format.setLineWidth(120);
    format.setIndenting(true);
    format.setIndent(2);
    format.setEncoding("UTF-8");
    return format;
}

public static String document2String(Document doc, OutputFormat format) throws Exception {
    StringWriter stringOut = new StringWriter();
    XMLSerializer serial = new XMLSerializer(stringOut, format);
    serial.serialize(doc);
    return stringOut.toString();
}

public static String document2String(Document doc) throws Exception {
    return XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}

public static void document2File(Document doc, File file) throws Exception {
    XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}

public static void document2File(Document doc, File file, OutputFormat format) throws Exception {
    XMLSerializer serializer = new XMLSerializer(new FileOutputStream(file), format);
    serializer.serialize(doc);
}
}

XMLserializer 由Apache Foundation的 xercesImpl 提供。这是maven依赖项:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>

您可以在此处找到您最喜欢的构建工具的依赖项:http: //mvnrepository.com/artifact/xerces/xercesImpl/2.11.0

于 2011-02-27T11:58:38.873 回答
1

您可能可以使用XSLT 文件美化所有内容。谷歌抛出了一些结果,但我无法评论它们的正确性。

于 2009-08-12T10:39:12.247 回答
0

要使输出成为有效的 XML 文档,NO。有效的 XML 文档必须以处理指令开头。有关详细信息,请参阅 XML 规范http://www.w3.org/TR/REC-xml/#sec-prolog-dtd

于 2013-06-19T17:55:47.077 回答