简体   繁体   中英

change XmlElement Name property

I would like to change the Name property of an XmlElement in c++/cli.

I would like to do myXmlElem.Name = "xyz" , but the compiler tells me that I can't do a set operation on the Name property.

ie

<abc/>

changed to

<xyz/>

How can I achieve this?

Thanks!

you can't change the Name property of an XmlElement like that (Name is read only).

you can however do something like the following (example in C#).

XmlElement xyz = myXmlElem.OwnerDocument.CreateElement("xyz");
myXmlElem.ParentNode.ReplaceChild(xyz, myXmlElem);

EDIT In response to your comment

XmlElement xyz = myXmlElem.OwnerDocument.CreateElement("xyz");

for(int i = 0; i < myXmlElem.ChildNodes.Count; i++){
    XmlNode child = myXmlElem.ChildNodes[i];
    xyz.AppendChild(child.CloneNode(true));
}

myXmlElem.ParentNode.ReplaceChild(xyz, myXmlElem);

You can use Linq to Xml which supports changing the name of an XElement:

XDocument doc = XDocument.Parse("<foo><bar /></foo>");
doc.Root.Name = "changed";//now it will look like <changed><bar /></changed>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM