将Xdocument soap响应主体解压缩到新的Xdocument中

时间:2016-09-17 09:28:33

标签: c# xml linq

我将XML解析为XDocument:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <MyResponse xmlns="https://www.domain.net/">
      <Node1>0</Node1>
    </MyResponse>
  </soap:Body>
</soap:Envelope>

基本上我正在尝试创建一个新的XDocument,其根目录为

<MyResponse xmlns="https://www.domain.net/">
      <Node1>0</Node1>
    </MyResponse>

所以从本质上讲,我试图从肥皂体中提取出来。我尝试使用Linq解析它,但似乎无法使用这个新root返回一个新的XDocument。有什么想法吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

我认为这会解决问题:

using System;
using System.Xml.Linq;

namespace SO39545160
{
  class Program
  {
    static string xmlSource = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
      "<soap:Body>" +
      "<MyResponse xmlns = \"https://www.domain.net/\" >" +
      "<Node1 > 0 </Node1 >" +
      "</MyResponse>" +
      "</soap:Body>" +
      "</soap:Envelope>";

    static void Main(string[] args)
    {
      XDocument xdoc = XDocument.Parse(xmlSource);
      var subXml = xdoc.Document.Elements(XName.Get(@"{http://schemas.xmlsoap.org/soap/envelope/}Envelope")).Elements(XName.Get(@"{http://schemas.xmlsoap.org/soap/envelope/}Body")).Elements(XName.Get(@"{https://www.domain.net/}MyResponse"));

      foreach (var node in subXml)
      {
        XDocument myRespDoc = new XDocument(node);
        Console.WriteLine(myRespDoc);
      }
      Console.WriteLine();

      Console.WriteLine("END");
      Console.ReadLine();
    }
  }
}