0

I have the following xdocument , I am trying to append item elements within the items element with the following code:

 xdocument.Root.Element("items").add(item)

This does not work as the items element can not be found. I think it is a problem with the namespaces but I can't seem to get this to work. Any help will be much appreciated.

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://mynamespace.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                                           <SOAP-ENV:Body>
                                               <ns1:getUpload>
                                                   <itemObj>
                                                       <items SOAP-ENC:arrayType="ns1:item[2]" xsi:type="ns1:ArrayOfItem">
                                                        <!--Item elements to go here-->
                                                       </items>
                                                   </itemObj>
                                               </ns1:getUpload>
                                           </SOAP-ENV:Body>
                                       </SOAP-ENV:Envelope>
fedor333
  • 45
  • 9

1 Answers1

1

It's because you <items> is not the direct child of your Root Element. Sticking this in a console app shows what is going on:

 var xd = XDocument.Load("xml.xml");

Console.WriteLine(xd.Root.Name); // {http://schemas.xmlsoap.org/soap/envelope/}Envelope
Console.WriteLine(xd.Root.Descendants("items").First().Name ); //items
Console.ReadKey();

Descendants checks through all children (and grand children etc) for the item named, Element only looks at direct children.

I am not sure on if Descendants is Depth First or Breadth First, so you may want to be careful on performance on huge documents.

Pondidum
  • 11,457
  • 8
  • 50
  • 69