简体   繁体   English

如何让 Java.xml.Transformer 输出一个没有任何无用空格或换行符的 xml?

[英]How to let Java.xml.Transformer output a xml without any useless space or line break?

My Code Now:我现在的代码:

import org.w3c.dom.Node;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

private String getStringByJAXP(Node input) {
        StreamResult xmlOutput;
        try {
            xmlOutput = new StreamResult(new StringWriter());
            transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(input), xmlOutput);
        } catch (TransformerException e) {
            throw new IllegalArgumentException();
        }
        return xmlOutput.getWriter().toString();
    }

Output:输出:

<aaa>
    <a>text a</a>
    <b>
        <c>text c</c>
    </b>
    <f>
        <g><h a="xxx"/></g>
    </f>
</aaa>

But I want to output as follows:但我想输出如下:

<aaa><a>text a</a><b><c>text c</c></b><f><g><h a="xxx" /></g></f></aaa>

Notice that I can't do that task by some simple string replaces, because the space in <a>text a</a> shouldn't be replaced( <a>texta</a> is total different from <a>text a</a> ).请注意,我无法通过一些简单的字符串替换来完成该任务,因为不应替换<a>text a</a>的空格( <a>texta</a><a>text a</a>完全不同<a>text a</a> )。

EDIT:编辑:

OutputKeys.INDENT, "no" not works. OutputKeys.INDENT, "no"不起作用。 Updated code:更新代码:

private String getStringByJAXP(Node input) {
    StreamResult xmlOutput;
    try {
        xmlOutput = new StreamResult(new StringWriter());
        transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(new DOMSource(input), xmlOutput);
    } catch (TransformerException e) {
        throw new IllegalArgumentException();
    }
    return xmlOutput.getWriter().toString();
}

I had a similar case once. 我有一次类似的案子。 I tried transformer.setOutputProperty(OutputKeys.INDENT,"no"); 我试过了transformer.setOutputProperty(OutputKeys.INDENT,“no”); first, but this did not work. 首先,但这不起作用。 The problem was that my original node had additional "new line" text nodes. 问题是我的原始节点有额外的“新行”文本节点。

The answer to Strip whitespace and newlines from XML in Java fixed it for me. 在Java中使用XML删除空格和换行符的答案为我修复了它。 Basically, you just remove the unnecessary text nodes before you transform the parent node. 基本上,您只需在转换父节点之前删除不必要的文本节点。

I ended up using this: 我最终使用了这个:

public static void trimWhitespace(Node node)
{
    NodeList children = node.getChildNodes();
    for(int i = 0; i < children.getLength(); ++i) {
        Node child = children.item(i);
        if(child.getNodeType() == Node.TEXT_NODE) {
            child.setTextContent(child.getTextContent().trim());
        }
        trimWhitespace(child);
    }
}

You can pass an XSLT stylesheet to your Transformer which has the advantage that you will not have to parse your document twice.您可以将 XSLT 样式表传递给您的 Transformer,其优点是您不必对文档进行两次解析。

InputStream xsltStream = getClass().getResourceAsStream("trim-whitespace.xslt");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsltStream));

trim-whitespace.xslt修剪-whitespace.xslt

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- copy all elements as they are -->
    <xsl:template match="*">
        <xsl:copy>
            <xsl:copy-of select="@*" />
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*/text()[not(normalize-space())]" />
</xsl:stylesheet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM