-3

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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vinod
  • 9
  • 1
  • 2
  • Please flag this for moderator attention once you've added language specifics, beyond XML so it can be re-opened. – Tim Post May 21 '11 at 17:11

1 Answers1

1

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);
svick
  • 236,525
  • 50
  • 385
  • 514