문제

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

도움이 되었습니까?

해결책

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

다른 팁

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"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top