【问题标题】:parsing SOAP xml with namespaces使用命名空间解析 SOAP xml
【发布时间】:2014-02-22 08:07:44
【问题描述】:

我一直在尝试解析一些信息并遵循http://lakenine.com/reading-xml-with-namespaces-using-linq/ 的精彩建议,我确信这已经接近了,但我没有得到任何结果显示。没有错误,只是没有结果。断点和检查变量表明 docx 具有正确的信息,但我的 for 循环被跳过了。我玩过多种变体,只设法使代码崩溃。我相信问题出在 XPathSelectElements 参数上,但不知道还能尝试什么。 在这个阶段,我需要的只是令牌,但我需要稍后重用代码来返回可能有多个结果的结果。请提前告知并感谢您:

        string sampleXML = String.Concat(
                "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
                " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"",
                " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">",
                " <soap12:Body>",
                " <BeginSessionV2Response xmlns=\"http://ws.jobboard.com/jobs/\">",
                " <BeginSessionV2Result>ca5522fb93ef499f8ed010a5f4153af7-446298346-SB-4</BeginSessionV2Result>",
                " </BeginSessionV2Response>",
                " </soap12:Body>",
                " </soap12:Envelope>"
                );

                XmlReader reader = XmlReader.Create(new StringReader(sampleXML));
                System.Xml.XmlNameTable nameTable = reader.NameTable;
                System.Xml.XmlNamespaceManager namespaceManager = new System.Xml.XmlNamespaceManager(nameTable);

                namespaceManager.AddNamespace("soap12", "http://www.w3.org/2001/XMLSchema-instance/");
                XElement docx = XElement.Load(reader);

                string vbResultz = "start: ";
                var sessionKey = from pn
                in docx.XPathSelectElements("soap12:Body/BeginSessionV2Response/BeginSessionV2Result", namespaceManager)
                     select (string)pn;
                        foreach (string pn in sessionKey)
                        {
                             vbResultz += pn;
                        }

                        ViewBag.REsultz = vbResultz;           


        return View();
    }

【问题讨论】:

    标签: c# asp.net-mvc-4 soap


    【解决方案1】:

    首先,您添加的 soap12 前缀有错误的 uri。以这种方式将命名空间添加到命名空间管理器:

    namespaceManager.AddNamespace("soap12", "http://www.w3.org/2003/05/soap-envelope");
    namespaceManager.AddNamespace("ns", "http://ws.jobboard.com/jobs/");
    

    然后你可以像这样在 XPath 表达式中使用它们:

    ......
    docx.XPathSelectElements("soap12:Body/ns:BeginSessionV2Response/ns:BeginSessionV2Result", namespaceManager)
    ......
    

    注意&lt;BeginSessionV2Response&gt; 具有默认命名空间(xmlns 属性不带前缀),因此该元素及其后代在默认命名空间内不考虑前缀。因此,我们需要在上面的 XPath 查询表达式中添加ns 前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 2014-01-10
      • 2012-12-05
      • 2010-11-08
      • 2018-07-15
      • 2012-06-11
      相关资源
      最近更新 更多