使用Java更改xml-node的节点名称 [英] Changing node name of xml-node with Java
问题描述
我有以下场景:我有一个XML文档,例如像这样
I have following scenario: I have a XML-Document, e.g. like this
<someRootElement>
<tag1>
<tag2
someKey=someValue
someKey2=someValue2
/>
<tag3/>
<tag4
newKey=newValue
newKey2=newValue2
/>
</tag1>
</someRootElement>
现在我希望将父 tag1 称为 reallyCoolTag 不丢失子节点。
我尝试了下面的内容,但不幸的是它没有按照我希望的方式工作(但我知道为什么,b / c它缺少一些东西,我猜):
Now I want the parent tag1 to be called reallyCoolTag without losing the childnodes. I tried the following, but it unfortunately doesn't work as I wish it would (but I do know why, b/c it is missing something, I guess):
// the new element:
Element neu = doc.createElement( newValue );
// append it to the root:
root.appendChild( neu );
// get all the child nodes:
NamedNodeMap nnm = nodes.item(i).getAttributes();
for( int dg = 0; dg < nnm.getLength(); dg++ ){
neu.setAttribute( nnm.item( dg ).getNodeName(),
nnm.item( dg ).getNodeValue() );
}
//---------------------------------------------------------
// HERE I GUESS I AM MISSING THE PART WHERE THE CHILD NODES
// ARE BEING APPENDED TO THE NEW NODE?????
//---------------------------------------------------------
// nodes.item(i) := the old value (nodes := is a NodeList
root.replaceChild( neu, nodes.item(i));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource( doc );
StreamResult result = new StreamResult( xml );
transformer.transform( source, result );
nodes.item( i ).getParentNode().removeChild( nodes.item(i) );
现在这确实有效,正如我所提到的,我想我错过了子节点所在的部分我真正想知道的是,是否有一个非常简短的方法来重命名父节点而不必复制所有内容并替换整个东西?
Now this does work to a certain extend, as I mentioned, I guess I am missing the part where the child nodes are being appened, but what I actually wanted to know is, whether there is a really short way to rename the parent node without having to copy everything and replace the whole thing?
Thnx提前!!!
Thnx in advance!!!
推荐答案
使用 Document.renameNode :
NodeList nodes = document.getElementsByTagName("tag1");
for (Node eachNode: nodes) {
document.renameNode(eachNode, null, "reallyCoolTag");
}
这篇关于使用Java更改xml-node的节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!