fedor333
fedor333

Reputation: 45

Appending Xelement to Xdocument

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>

Upvotes: 0

Views: 1226

Answers (1)

Pondidum
Pondidum

Reputation: 11637

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.

Upvotes: 1

Related Questions