Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert an XElement into an existing xml-file?

I do have following xml:

<Assembly>
  <Bench>
    <Typ>P1</Typ>
    <DUT>
       <A>6</A>
     </DUT>
  </Bench>
  <Bench>
    <Typ>P2</Typ>
     <DUT>
       <A>6</A>
     </DUT>
  </Bench>
</Assembly>

How can I get a reference to 'P2'-element that I can insert a new DUT? I tried following code which gives me an error:

var xElement = xmlDoc.Element("Assembly")
                                .Elements("Bench")
                                .Where(item => item.Attribute("Typ").Value == "P2")
                                .FirstOrDefault();

xElement.AddAfterSelf(new XElement("DUT")); 

thanks in advance

like image 672
Norick Avatar asked Oct 01 '22 21:10

Norick


2 Answers

Typ is element name, not an attribute. If you meant to add new <DUT> element after existing <DUT> under the second <Bench>, this slight change to the code you've tried should work :

var xElement = xmlDoc.Element("Assembly")
                     .Elements("Bench")
                     .FirstOrDefault(item => item.Element("Typ").Value == "P2");

xElement.AddAfterSelf(new XElement("DUT")); 
like image 189
har07 Avatar answered Oct 03 '22 12:10

har07


Another way of doing the same thing, just to show the options available.

XElement typ = xmlDoc.Descentants("Typ")
                     .FirstOrDefault(typ => ((string)typ) == "P2");

You can use the same AddAfterSelf as har07, or .Parent.Add() if it doesn't matter where in the parent Bench it goes. Add will add it as the last element.

typ.Parent.Add(new XElement("DUT"));
like image 38
Chuck Savage Avatar answered Oct 03 '22 12:10

Chuck Savage