change XmlElement Name property

2019-08-12 05:29发布

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.

i.e.

<abc/>

changed to

<xyz/>

How can I achieve this?

Thanks!

2条回答
Fickle 薄情
2楼-- · 2019-08-12 06:08

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);
查看更多
Anthone
3楼-- · 2019-08-12 06:10

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>
查看更多
登录 后发表回答