开发者

How to add new XML element to existing NodeList? [closed]

开发者 https://www.devze.com 2023-03-07 17:07 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_如何学Python Closed 11 years ago.

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消