pjeung wrote:
Say that I have an element <elementA> that has several layers of subelements.
In System.Xml.XmlD ocument and related classes, how do I rename <elementA> to <elementB> leaving the subelements intact?
I think you have to write your own code that creates a new element with
the desired name, then you need to move the attribute and child nodes to
the new element and finally you need to replace the old element with the
new element. Here is a C# example that does that for element nodes:
using System;
using System.Xml;
public class Test20040721 {
public static void Main (string[] args) {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Loa d(@"test2004072 101.xml");
Console.WriteLi ne(xmlDocument. OuterXml);
XmlElement element = (XmlElement)
xmlDocument.Get ElementsByTagNa me("element")[0];
XmlElement renamedElement = (XmlElement) RenameNode(elem ent, null,
"new-element");
Console.WriteLi ne(xmlDocument. OuterXml);
}
public static XmlNode RenameNode (XmlNode node, string namespaceURI,
string qualifiedName) {
if (node.NodeType == XmlNodeType.Ele ment) {
XmlElement oldElement = (XmlElement) node;
XmlElement newElement =
node.OwnerDocum ent.CreateEleme nt(qualifiedNam e, namespaceURI);
while (oldElement.Has Attributes) {
newElement.SetA ttributeNode(ol dElement.Remove AttributeNode(o ldElement.Attri butes[0]));
}
while (oldElement.Has ChildNodes) {
newElement.Appe ndChild(oldElem ent.FirstChild) ;
}
if (oldElement.Par entNode != null) {
oldElement.Pare ntNode.ReplaceC hild(newElement , oldElement);
}
return newElement;
}
else {
return null;
}
}
}
The example I have tested that one is
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element att1="value 1" att2="value ">
<child />
<god name="Kibo" />
</element>
</root>
the output is
<?xml version="1.0" encoding="UTF-8"?><root><elem ent att1="value 1"
att2="value"><c hild /><god name="Kibo" /></element></root>
<?xml version="1.0" encoding="UTF-8"?><root><n ew-element att1="value 1"
att2="value "><child /><god name="Kibo" /></new-element></root>
so the element is renamed and attributes and child nodes have been
preserved that way.
The W3C DOM Level 3 Core module suggests a method named renameNode at
http://www.w3.org/TR/DOM-Level-3-Cor...nt3-renameNode
but that is not implemented in .NET, not even in the .NET 2.0 beta as
far as I can tell.
--
Martin Honnen
http://JavaScript.FAQTs.com/