【问题标题】:How to process all nodes in a Nodelist如何处理节点列表中的所有节点
【发布时间】:2014-12-17 00:54:39
【问题描述】:

我正在尝试处理节点列表中的所有节点并替换文本中的特殊字符。

我面临的问题是我需要返回一个包含所有替换值的对象。如果我使用递归,这不可能返回一个值吗?

如何迭代处理所有元素并删除特殊字符的 xml 节点列表?我目前的方法是这样做

public static IXMLDatagram removeIllegalCharsFromDataGram(IXMLDatagram dg, String[] illegalValues)
{
    NodeList nodeList = dg.getAsDOMElement().getElementsByTagName("*");
    for (int i = 0 ; i < nodeList.getLength() ; i++)
    {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE)
        {

            for(String replaceChar : illegalValues)
            {
                // do something with the current element
                if(node.getTextContent().contains(replaceChar))
                {
                    node.setTextContent(node.getTextContent().replace(replaceChar, ""));
                }
            }
        }
    }
    return dg;
}

但这并没有考虑在这些文档中定期更改并且通常嵌套很深的子节点

谢谢

【问题讨论】:

  • 您可以预先迭代所有节点/列表,将它们全部放在某种List 中,然后改为处理List
  • 然后我将如何将节点替换回原始对象中?
  • 为什么需要?您正在修改物理对象的内容,它们尚未从 DOM 中删除,您只是在维护对它们的引用...
  • 有意思,我试试这个方法

标签: java xml recursion nodelist


【解决方案1】:

递归通常是深度处理 DOM 最简单的方法:

public static void removeIllegalCharsFromDataGram(IXMLDatagram dg,
        String[] illegalValues) {
    Node root = dg.getAsDOMElement().getDocumentElement();
    removeIllegal(illegalValues, root);
}
private static void removeIllegal(String[] illegalValues, Node root) {
    NodeList nodeList = root.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);

        removeIllegal(illegalValues,node);//<-- Call for every child

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            for (String replaceChar : illegalValues) {
                // do something with the current element
                if (node.getTextContent().contains(replaceChar)) {
                    node.setTextContent(node.getTextContent().replace(
                            replaceChar, ""));
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多