开发者

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:Envelo开发者_开发百科pe 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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜