Share via


Insert a XElement into another XElement at a specific spot

Question

Thursday, August 20, 2009 3:29 PM

Is there anyway of placing a XElement node into another XElement node or XDocument at a specific position, e.g.:

<newnode>bla</newnode>

BEFORE INSERTION:

<oldnode>

  <whatever>stuff</whatever>

  <what>morestuff</what>

</oldnode>

AFTER INSERTION:

<oldnode>

  <whatever>stuff</whatever> 

  <newnode>bla</newnode>

  <what>morestuff</what>

</oldnode>

All replies (5)

Thursday, August 20, 2009 3:43 PM âś…Answered | 1 vote

Changing the XML file to this:

  <oldnode>
    <first>1</first>
    <second>2</second>
  </oldnode> 

This is the code:

            // Define the new element
            XElement newElement = XElement.Parse(@"<newnode>bla</newnode>");

            // Find the insertion location
            XElement parentElement = xDoc.Descendants("first").FirstOrDefault();
            if (parentElement != null)
                parentElement.AddAfterSelf(newElement);

            Debug.WriteLine(xDoc.Descendants("oldnode").FirstOrDefault());

www.insteptech.com ; msmvps.com/blogs/deborahk
We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!


Thursday, August 20, 2009 3:34 PM

I was going to try this ... but my XML editor does not alow <1> or <2> to be used as XML tags. Are you able to use this XML file "as is"?www.insteptech.com ; msmvps.com/blogs/deborahk
We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!


Thursday, August 20, 2009 3:35 PM

Yeah it doesn't matter any xml files.


Thursday, August 20, 2009 3:36 PM

Yeah it doesn't matter any xml files.

Your xml is malformed. Element names cannot start with a number.http://blog.voidnish.com


Thursday, August 20, 2009 3:45 PM

Use something like this :

string xml = @"<oldnode>
<whatever>stuff</whatever>
<what>morestuff</what>
</oldnode>";

XDocument doc = XDocument.Parse(xml);
doc.Descendants("whatever").First().AddAfterSelf(
    new XElement("newnode", "blah"));

string newXml = doc.ToString();
Console.WriteLine(newXml);

http://blog.voidnish.com