如何从XML节点用C# - 我究竟做错了什么? [英] How to get a node from xml with c#- what am I doing wrong?

查看:133
本文介绍了如何从XML节点用C# - 我究竟做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命名空间和XML仍然扑朔迷离了我的地狱。

Namespaces and XML are still confusing the hell out of me.

下面是我的XML(来自SOAP请求)

Here is my XML (that comes from a SOAP request)

<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="http://tempuri.org/">
         <OutputXML xmlns="http://tempuri.org/XMLSchema.xsd">
            <Result>
               <OutputXML>
                  <Result>
                     <Foo>
                        <Bar />
                     </Foo>
                  </Result>
               </OutputXML>
            </Result>
         </OutputXML>
      </MyResponse>
   </soap:Body>
</soap:Envelope>



我试图提取实际的XML部分来自SOAP响应(与富元素开始):

I am trying to extract the actual XML part from the SOAP response (starting with the Foo element):

var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("", "http://tempuri.org/");
nsmgr.AddNamespace("", "http://tempuri.org/XMLSchema.xsd");

var xml = document.DocumentElement
    .SelectSingleNode("Foo", nsmgr)
    .InnerXml;



不过的SelectSingleNode返回null。我已经试过这方面的一些不同的变化,但不能得到任何工作。什么是我不理解

But SelectSingleNode returns null. I've tried some different variations on this but can't get anything working. What am I not understanding?

推荐答案

试试这个:

var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("aaa", "http://tempuri.org/XMLSchema.xsd");

var xml = document.DocumentElement
    .SelectSingleNode("aaa:Foo", nsmgr)
    .InnerXml;

这是因为默认名称空间的 无。perfix

this is because of Default namespaces has no perfix.

您可以使用的getElementsByTagName 使用命名空间URI直接:

You can use GetElementsByTagName to use namespace uri directly:

var xml = document.GetElementsByTagName("Foo", 
             "http://tempuri.org/XMLSchema.xsd")[0].InnerXml;

这篇关于如何从XML节点用C# - 我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆