如何在序列化之前从DOM中删除仅包含空格的文本节点?

19

我有一些使用Java(5.0)编写的代码,该代码从各种(缓存的)数据源构建DOM,然后删除不需要的某些元素节点,最后使用以下方法将结果序列化为XML字符串:

// Serialize DOM back into a string
Writer out = new StringWriter();
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "no");
tf.transform(new DOMSource(doc), new StreamResult(out));
return out.toString();

然而,由于我要删除几个元素节点,最终序列化的文档中会有很多额外的空格。

有没有一种简单的方法在DOM被序列化成字符串之前(或同时)从中删除/折叠多余的空格?

7个回答

39

您可以使用XPath查找空文本节点,然后通过编程方式将其移除,如下所示:

XPathFactory xpathFactory = XPathFactory.newInstance();
// XPath to find empty text nodes.
XPathExpression xpathExp = xpathFactory.newXPath().compile(
        "//text()[normalize-space(.) = '']");  
NodeList emptyTextNodes = (NodeList) 
        xpathExp.evaluate(doc, XPathConstants.NODESET);

// Remove each empty text node from document.
for (int i = 0; i < emptyTextNodes.getLength(); i++) {
    Node emptyTextNode = emptyTextNodes.item(i);
    emptyTextNode.getParentNode().removeChild(emptyTextNode);
}

如果您想在节点删除方面获得比使用XSL模板更多的控制,则此方法可能非常有用。


我更喜欢这个“仅代码”解决方案,甚至比XSL解决方案更好,正如你所说,如果需要,可以更好地控制节点的删除。 - Marc Novakowski
2
顺便说一下,如果在删除节点之前先调用 doc.normalize() 这个方法似乎才能正常工作。我不确定为什么这样做会有所区别。 - Marc Novakowski
3
非常好的答案。即使没有normalize()函数,对我也有效。 - james.garriss
2
@MarcNovakowski 这是一个需要调用 normalize() 方法的示例。将一些 XML 字符串加载到 DOM 对象中。调用 removeChild() 方法从 DOM 对象中获取一些节点。然后尝试像当前答案中那样去除空格 (//text()[normalize-space(.) = ''])。在删除节点时会出现空行。如果先调用 normalize(),则不会发生这种情况。 - Stephan

8
尝试使用以下XSL和strip-space元素来序列化您的DOM:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" omit-xml-declaration="yes"/>

  <xsl:strip-space elements="*"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
     <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

http://helpdesk.objects.com.au/java/how-do-i-remove-whitespace-from-an-xml-document


4

以下代码删除所有空白处的注释节点和文本节点。如果文本节点具有某些值,则该值将被修剪

public static void clean(Node node)
{
  NodeList childNodes = node.getChildNodes();

  for (int n = childNodes.getLength() - 1; n >= 0; n--)
  {
     Node child = childNodes.item(n);
     short nodeType = child.getNodeType();

     if (nodeType == Node.ELEMENT_NODE)
        clean(child);
     else if (nodeType == Node.TEXT_NODE)
     {
        String trimmedNodeVal = child.getNodeValue().trim();
        if (trimmedNodeVal.length() == 0)
           node.removeChild(child);
        else
           child.setNodeValue(trimmedNodeVal);
     }
     else if (nodeType == Node.COMMENT_NODE)
        node.removeChild(child);
  }
}

参考:http://www.sitepoint.com/removing-useless-nodes-from-the-dom/ 本文将介绍如何从DOM中删除无用节点。

该方法适用于小型XML,但不适用于具有大量嵌套节点的大型XML。对于4K条记录,处理它需要约30秒的时间。 我建议将XML作为字符串读取,然后使用xmlString.replaceAll("\\p{javaWhitespace}+", "");,这样速度会更快。 - NIGAGA

0
另一种可能的方法是在删除目标节点的同时删除相邻的空格:
private void removeNodeAndTrailingWhitespace(Node node) {
    List<Node> exiles = new ArrayList<Node>();

    exiles.add(node);
    for (Node whitespace = node.getNextSibling();
            whitespace != null && whitespace.getNodeType() == Node.TEXT_NODE && whitespace.getTextContent().matches("\\s*");
            whitespace = whitespace.getNextSibling()) {
        exiles.add(whitespace);
    }

    for (Node exile: exiles) {
        exile.getParentNode().removeChild(exile);
    }
}

这样做的好处是保持现有格式的完整性。


0
以下代码有效:
public String getSoapXmlFormatted(String pXml) {
    try {
        if (pXml != null) {
            DocumentBuilderFactory tDbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder tDBuilder;
            tDBuilder = tDbFactory.newDocumentBuilder();
            Document tDoc = tDBuilder.parse(new InputSource(
                    new StringReader(pXml)));
            removeWhitespaces(tDoc);
            final DOMImplementationRegistry tRegistry = DOMImplementationRegistry
                    .newInstance();
            final DOMImplementationLS tImpl = (DOMImplementationLS) tRegistry
                    .getDOMImplementation("LS");
            final LSSerializer tWriter = tImpl.createLSSerializer();
            tWriter.getDomConfig().setParameter("format-pretty-print",
                    Boolean.FALSE);
            tWriter.getDomConfig().setParameter(
                    "element-content-whitespace", Boolean.TRUE);
            pXml = tWriter.writeToString(tDoc);
        }
    } catch (RuntimeException | ParserConfigurationException | SAXException
            | IOException | ClassNotFoundException | InstantiationException
            | IllegalAccessException tE) {
        tE.printStackTrace();
    }
    return pXml;
}

public void removeWhitespaces(Node pRootNode) {
    if (pRootNode != null) {
        NodeList tList = pRootNode.getChildNodes();
        if (tList != null && tList.getLength() > 0) {
            ArrayList<Node> tRemoveNodeList = new ArrayList<Node>();
            for (int i = 0; i < tList.getLength(); i++) {
                Node tChildNode = tList.item(i);
                if (tChildNode.getNodeType() == Node.TEXT_NODE) {
                    if (tChildNode.getTextContent() == null
                            || "".equals(tChildNode.getTextContent().trim()))
                        tRemoveNodeList.add(tChildNode);
                } else
                    removeWhitespaces(tChildNode);
            }
            for (Node tRemoveNode : tRemoveNodeList) {
                pRootNode.removeChild(tRemoveNode);
            }
        }
    }
}

这个答案如果能加上一些解释会更好。 - Eiko

0

我是这样做的

    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s*", Pattern.DOTALL);

    private void removeWhitespace(Document doc) {
        LinkedList<NodeList> stack = new LinkedList<>();
        stack.add(doc.getDocumentElement().getChildNodes());
        while (!stack.isEmpty()) {
            NodeList nodeList = stack.removeFirst();
            for (int i = nodeList.getLength() - 1; i >= 0; --i) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.TEXT_NODE) {
                    if (WHITESPACE_PATTERN.matcher(node.getTextContent()).matches()) {
                        node.getParentNode().removeChild(node);
                    }
                } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                    stack.add(node.getChildNodes());
                }
            }
        }
    }


-3
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

这将保留xml的缩进。


2
它不会去除多余的空格。 - Thorbjørn Ravn Andersen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接