通过Java替换XML节点 [英] Replacing XML node via Java
本文介绍了通过Java替换XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用另一个节点替换XML文档中的节点,因此用其他内容替换它的所有子节点。以下代码应该有效,但由于未知原因,它不会。
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.
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");
}
编辑 -
经过一段时间的调试后,我解决了它。问题在于移动子阵列elmts的索引。这是代码:
After debugging it for a while, I sovled it. The problem was in moving index of the children array elmts. Here's the code:
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");
}
推荐答案
尝试使用replaceChild来执行整个层次结构:
Try using replaceChild to do the whole hierarchy at once:
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);
}
这篇关于通过Java替换XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文