Question

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

Was it helpful?

Solution

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

OTHER TIPS

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"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top