java 如何重命名 XML 节点名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6531129/
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
How to rename XML node name
提问by RAAAAM
I want to rename the existing XML node into new name. I am doing XML parsing using DOM concept java, i have set of node which contains same name. for example
我想将现有的 XML 节点重命名为新名称。我正在使用 DOM 概念 java 进行 XML 解析,我有一组包含相同名称的节点。例如
<names>
<abc>Apple</abc>
<abc>Ball</abc>
<abc>Cat</abc>
<abc>Doll</abc>
<abc>Elephant</abc>
</names>
I the above example there is set of nodes contains value. in that example i want to change the node value (ie)
我上面的例子有一组节点包含值。在那个例子中,我想改变节点值(即)
<names>
<name>Apple</name>
<name>Ball</name>
<name>Cat</name>
<name>Doll</name>
<name>Elephant</name>
</names>
is this possible to do in DOM, i am pretty much new to parsing concept using DOM.. Thanks for valuable comments.
这是否可以在 DOM 中完成,我对使用 DOM 解析概念非常陌生。感谢您的宝贵意见。
回答by Ron
Similar to my answer in updating a property of a xml tag:
类似于我在更新 xml 标记的属性时的回答:
public void changeTagName(Document doc, String tag, String fromTag, String toTag) {
NodeList nodes = doc.getElementsByTagName(fromTag);
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i) instanceof Element) {
Element elem = (Element)nodes.item(i);
doc.renameNode(elem, elem.getNamespaceURI(), toTag);
}
}
}