Frage

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

War es hilfreich?

Lösung

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

Andere Tipps

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"));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top