How to add new XML element to existing NodeList? [closed]
Suppose I have
<Start>
<abc>
...
..
</abc>
<qqq id = 1>
...
...
...
</qqq>
<qqq id = 2>
...
...
...
</qqq>
</Start>
Is it possible to create new element in this kind of XML so that it takes all <qqq>
's as child nodes ?
I.e, the final XML should look like this:
<Start>
<abc>
...
...
</abc>
<Begin name = myname>
<qqq id = 1>
...
...
...
</qqq>
<qqq id = 2>
...
...
...
</qqq>
</Begin>
</Start>
Assuming you're using C# and you want to use XmlDocument
, you could do it like this:
var doc = new XmlDocument();
doc.LoadXml(xml);
var root = doc.DocumentElement;
var begin = doc.CreateElement("Begin");
var beginAttribute = doc.CreateAttribute("name");
beginAttribute.Value = "myname";
begin.Attributes.Append(beginAttribute);
var qqqs = root.GetElementsByTagName("qqq").Cast<XmlNode>().ToArray();
foreach (XmlNode qqq in qqqs)
{
root.RemoveChild(qqq);
begin.AppendChild(qqq);
}
root.AppendChild(begin);
But using XDocument
is much easier:
var doc = XDocument.Parse(xml);
var qqqs = doc.Root.Elements("qqq");
var begin = new XElement("Begin", new XAttribute("name", "myname"), qqqs);
qqqs.Remove();
doc.Root.Add(begin);
精彩评论