Write an org.w3.dom.Document to a File – 将org.w3.dom.Document写到一个文件中

最后修改: 2018年 10月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

An important part of XML handling is creating XML files that can be consumed by others.

XML处理的一个重要部分是创建可被他人消费的XML文件。

When handling XML in Java, we’ll often have an instance of org.w3c.dom.Document that we need to export.

在Java中处理XML时,我们经常会有一个org.w3c.dom.Document的实例,我们需要导出它。

In this quick tutorial, we’ll see how to write a Document to a file both in an in-line as well as a pretty-printed format.

在这个快速教程中,我们将看到如何将一个Document以内联和漂亮的打印格式写入一个文件

2. Using a Transformer

2.使用变压器

The heavy-lifter when writing Documents to files is javax.xml.transform.Transformer.

Documents写入文件时的重头戏是javax.xml.transform.Transformer.

2.1. Creating the Transformer

2.1.创建转化器

So, let’s start by getting a TransformerFactory. We’ll use this factory to create the transformer:

因此,让我们从获得一个TransformerFactory开始。我们将使用这个工厂来创建转化器。

TransformerFactory transformerFactory = TransformerFactory.newInstance()

The system property javax.xml.transform.TransformerFactory specifies which factory implementation to create. Consequently, this property names a concrete subclass of the TransformerFactory abstract class. But, if we don’t define this property, the transformer will simply use a platform default.

系统属性javax.xml.transformerFactory指定了要创建的工厂实现。因此,该属性命名了TransformerFactory抽象类的一个具体子类。但是,如果我们不定义这个属性,转化器将简单地使用一个平台默认值。

Note that since Java 9, we can use TransformerFactory.newDefaultInstance() to create the built-in system-default implementation.

注意,自Java 9以来,我们可以使用TransformerFactory.newDefaultInstance()来创建内置的系统默认实现。

Now that we have the factory, let’s create the Transformer:

现在我们有了工厂,让我们来创建Transformer

Transformer transformer = transformerFactory.newTransformer();

2.2. Specifying the Source and Result

2.2.指定来源和结果

The Transformer transforms a source into a result. In our case, the source is the XML document and the result is the output file.

Transformer将一个源转化为一个结果。在我们的例子中,源是XML文档,结果是输出文件。

First, let’s specify the source of the transformation. Here, we’ll use our Document to construct a DOM source:

首先,让我们指定转换的源。这里,我们将使用我们的Document来构建一个DOM源。

DOMSource source = new DOMSource(document);

Note that the source doesn’t have to be the whole document. So long as the XML is well-formed, we can use a sub-tree of the document.

注意,源不一定是整个文档。只要XML的格式良好,我们就可以使用文档的一个子树。

Next, we’ll specify where the transformer should write the result of the transformation:

接下来,我们将指定转化器应该把转化的结果写在哪里。

FileWriter writer = new FileWriter(new File(fileName));
StreamResult result = new StreamResult(writer);

Here, we’re telling the transformer that the result is a file stream. But, we can use any kind of java.io.Writer or java.io.OutputStream to create the StreamResult. For example, we could use a StringWriter to construct a String that can then be logged.

在这里,我们告诉转化器,结果是一个文件流。但是,我们可以使用任何类型的java.io.Writer java.io.OutputStream来创建StreamResult。例如,我们可以使用StringWriter 来构建一个String,然后可以被记录。

2.3. Creating the XML File

2.3.创建XML文件

Finally, we’ll tell the transformer to operate on the source object and output to the result object:

最后,我们将告诉转化器对源对象进行操作,并输出到结果对象。

transformer.transform(source, result);

This will finally create a file with the contents of the XML document:

这将最终创建一个包含XML文档内容的文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Company><Department name="Sales">
  <Employee name="John Smith"/><Employee name="Tim Dellor"/></Department></Company>

3. Customizing the Output

3.自定义输出

We can customize the XML written to the file by specifying a variety of output propertiesLet’s explore a few of these.

我们可以通过指定各种输出属性来定制写入文件的 XML让我们来探讨一下其中的几个。

3.1. Pretty-Printing the Output

3.1.漂亮地打印输出

Now, our default transformer simply wrote everything onto a single line, which isn’t as pleasant to read. Indeed, it would be even more difficult to read if the XML were large.

现在,我们的默认转化器只是把所有的东西都写到了一个单行上,这并不那么令人愉快。事实上,如果XML很大的话,它甚至会更难读。

We can configure our transformer for pretty-printing by setting the OutputKeys.INDENT property on the transformer:

我们可以通过在转化器上设置OutputKeys.INDENT属性来配置我们的转化器以实现漂亮的打印:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

Notice that along with the OutputKeys.INDENT, we have also specified the indent-amount property here. This will indent the output correctly, as by default the indentation is zero spaces.

注意,除了OutputKeys.INDENT,我们还在这里指定了indent-amount属性。这将正确地缩进输出,因为默认情况下,缩进是零空间。

With the above properties set, we get a much nicer output:

通过上述属性的设置,我们得到了一个更漂亮的输出。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Company>
    <Department name="Sales">
        <Employee name="John Smith"/>
        <Employee name="Tim Dellor"/>
    </Department>
</Company>

3.2. Omitting the XML Declaration

3.2.省略XML声明

Sometimes, we might want to exclude the XML declaration.

有时,我们可能想排除XML声明。

We can configure our transformer to do this by setting the OutputKeys.OMIT_XML_DECLARATION property:

我们可以通过设置OutputKeys.OMIT_XML_DECLARATION属性来配置我们的转化器来做到这一点。

transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

And using our transformer again, we get:

再次使用我们的变压器,我们得到。

<Company>
    <Department name="Sales">
        <Employee name="John Smith"/>
        <Employee name="Tim Dellor"/>
    </Department>
</Company>

3.3. Other Output Properties

3.3.其他输出属性

So, apart from pretty-printing and omitting the XML declaration, we can customize the output in other ways, too:

因此,除了漂亮的打印和省略XML声明之外,我们还可以通过其他方式定制输出。

  • We can specify the XML version using OutputKeys.VERSION, the default is “1.0”
  • We can indicate our preferred character encoding using OutputKeys.ENCODING, the default is “utf-8”
  • And, we can also specify other typical declaration attributes like SYSTEMPUBLIC, and STANDALONE.

4. Conclusion

4.结论

In this tutorial, we saw how to export an org.w3c.Document to a file and how to customize the output.

在本教程中,我们看到了如何将一个org.w3c.Document导出到一个文件,以及如何自定义输出。

And, of course, the accompanying source code is available over on GitHub.

当然,随附的源代码可以在GitHub上获得