【问题标题】:Namespace Manager or XsltContext needed需要命名空间管理器或 XsltContext
【发布时间】:2011-08-17 05:23:24
【问题描述】:

我有以下xml;

   <env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
   <env:Header>
       <mm7:TransactionID xmlns:mm7='http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4' env:mustUnderstand='1'>6797324d</mm7:TransactionID>
   </env:Header>
   <env:Body>
       <DeliveryReportReq xmlns='http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4'>
           <MM7Version>6.8.0</MM7Version><MMSRelayServerID>TARAL</MMSRelayServerID>
           <MessageID>T*3*T\*4\*855419761</MessageID>
           <Recipient>
               <RFC2822Address>+61438922562/TYPE=hidden</RFC2822Address>
           </Recipient>
           <Sender>
               <RFC2822Address>61418225661/TYPE=hidden</RFC2822Address>
           </Sender>
           <Date>2011-08-15T12:57:27+10:00</Date>
           <MMStatus>Retrieved</MMStatus>
           <StatusText>The message was retrieved by the recipient</StatusText>
       </DeliveryReportReq>   
   </env:Body>
 </env:Envelope>

那么我有以下c#代码;

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(file);
XmlNode xNode = xDoc.SelectSingleNode("env:Envelope");

我得到了错误;

需要命名空间管理器或 XsltContext。此查询具有前缀、变量或用户定义的函数。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    我个人会改用 LINQ to XML - 它的命名空间支持更容易掌握。鉴于Envelope 只是根节点 - 为什么不直接请求根节点

    但是,如果你真的想使用 XPath,你可以从XmlDocument 中的名称表中创建一个新的XmlNamespaceManager,注册一个前缀,然后将命名空间管理器传递给SelectSingleNode overload which takes one.

    this answer 中有一些示例代码,但如果可以的话,我再次强烈建议您考虑其他方法……特别是使用 LINQ to XML,其中搜索(比如说)所有“env:Body”元素(这里只有一个,但是...)看起来像这样:

    XNamespace env = "http://schemas.xmlsoap.org/soap/envelope/";
    var bodies = doc.Descendants(env + "Body");
    

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2012-06-27
      • 2019-10-05
      相关资源
      最近更新 更多