本文介绍了来自 javax.xml.transform.Transformer 的漂亮打印输出,只有标准的 java api(缩进和文档类型定位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下简单代码:

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 标签出现在文档注释之后.是否可以让它出现在文档注释之前?

Question A: The doctype tag appears after the document comment. Is it possible to make it appear before the document comment?

问题 B:如何仅使用 JavaSE 5.0 API 实现缩进?这个问题本质上与如何从java中漂亮地打印xml相同,然而该问题的几乎所有答案都依赖于外部库.唯一适用的答案(由名为 Lorenzo Boccaccia 的用户发布)仅使用 java 的 api,基本上与上面发布的代码相同,但对我不起作用(如输出所示,我没有缩进).

Question B: How do I achieve indentation, using only the JavaSE 5.0 API?This question is essentially identical to How to pretty-print xml from java, however almost all answers in that question depend on external libraries. The only applicable answer (posted by a user named Lorenzo Boccaccia) which only uses java's api, is basically equal to the code posted above, but does not work for me (as shown in the output, i get no indentation).

我猜您必须设置用于缩进的空格量,正如许多外部库的答案所做的那样,但我只是找不到在 java api 中指定的位置.鉴于在 java api 中存在将缩进属性设置为是"的可能性,必须可以以某种方式执行缩进.我就是不知道怎么做.

I am guessing that you have to set the amount of spaces to use for indentation, as many of the answers with external libraries do, but I just cannot find where to specify that in the java api. Given the fact that the possibility to set an indentation property to "yes" exists in the java api, it must be possible to perform indentation somehow. I just can't figure out how.

推荐答案

缺少的部分是缩进量.您可以按如下方式设置缩进和缩进量:

The missing part is the amount to indent. You can set the indentation and indent amount as follow:

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

这篇关于来自 javax.xml.transform.Transformer 的漂亮打印输出,只有标准的 java api(缩进和文档类型定位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:21