Groups | Blog | Home
all groups > dotnet xml > july 2004 >

dotnet xml : Renaming an element


pjeung
7/21/2004 1:21:02 AM
Say that I have an element <elementA> that has several layers of subelements.
Martin Honnen
7/21/2004 2:04:04 PM


[quoted text, click to view]

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.Load(@"test2004072101.xml");
Console.WriteLine(xmlDocument.OuterXml);
XmlElement element = (XmlElement)
xmlDocument.GetElementsByTagName("element")[0];
XmlElement renamedElement = (XmlElement) RenameNode(element, null,
"new-element");
Console.WriteLine(xmlDocument.OuterXml);
}

public static XmlNode RenameNode (XmlNode node, string namespaceURI,
string qualifiedName) {
if (node.NodeType == XmlNodeType.Element) {
XmlElement oldElement = (XmlElement) node;
XmlElement newElement =
node.OwnerDocument.CreateElement(qualifiedName, namespaceURI);
while (oldElement.HasAttributes) {

newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0]));
}
while (oldElement.HasChildNodes) {
newElement.AppendChild(oldElement.FirstChild);
}
if (oldElement.ParentNode != null) {
oldElement.ParentNode.ReplaceChild(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><element att1="value 1"
att2="value"><child /><god name="Kibo" /></element></root>
<?xml version="1.0" encoding="UTF-8"?><root><new-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-Core/core.html#Document3-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/
AddThis Social Bookmark Button