0

我有以下 xdocument ,我正在尝试使用以下代码在 items 元素中附加 item 元素:

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

这不起作用,因为找不到 items 元素。我认为这是命名空间的问题,但我似乎无法让它工作。任何帮助都感激不尽。

<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>
4

1 回答 1

1

这是因为你<items>不是你的根元素的直接孩子。将其粘贴在控制台应用程序中可以显示发生了什么:

 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检查命名项目的所有子项(和孙子等),Element只查看直接子项。

我不确定 Descendants 是深度优先还是广度优先,因此您可能需要小心处理大型文档的性能。

于 2010-11-09T11:27:58.867 回答