通过 Java 替换 XML 节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7903957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:54:57  来源:igfitidea点击:

Replacing XML node via Java

javaxml

提问by Ondrej Sotolar

I wan to replace a node in XML document with another and as a consequence replace all it's children with other content. Following code should work, but for an unknown reason it doesn't.

我想用另一个替换 XML 文档中的一个节点,因此用其他内容替换它的所有子节点。以下代码应该可以工作,但由于未知原因,它不起作用。

File xmlFile = new File("c:\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {

    NodeList children = nodes.item(i).getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
          nodes.item(i).removeChild(children.item(j));
    }
        doc.renameNode(nodes.item(i), null, "MyCustomTag");  
}

EDIT-

编辑-

After debugging it for a while, I sovled it. The problem was in moving index of the children array elmts. Here's the code:

调试了一段时间后,我解决了它。问题在于移动子数组 elmts 的索引。这是代码:

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {

    NodeList children = nodes.item(i).getChildNodes();

    int len = children.getLength();
    for (int j = len-1; j >= 0; j--) {
        nodes.item(i).removeChild((Node) children.item(j));
    }
    doc.renameNode(nodes.item(i), null, "MyCustomTag");  
}

回答by Thor84no

Try using replaceChild to do the whole hierarchy at once:

尝试使用 replaceChild 一次完成整个层次结构:

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    Node newNode = // Create your new node here.
    node.getParentNode().replaceChild(newNode, node);
}

回答by Venkat

Easy way to do is using regular expression.

简单的方法是使用正则表达式。

String payload= payload.replaceAll("<payload>([^<]*)</payload>", "<payload>NODATA</payload>");

This will make sure all the payload nodes contents are replaced with NODATA

这将确保所有有效负载节点的内容都替换为 NODATA