需要命名空间管理器或XsltContext
本文关键字:XsltContext 管理器 命名空间 | 更新日期: 2023-09-27 18:05:43
我有以下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");
得到错误;
Namespace Manager或XsltContext需要。该查询具有前缀、变量或用户定义函数。
有人知道如何解决这个问题吗?
我个人倾向于使用LINQ to XML——它的命名空间支持更容易掌握。既然Envelope
只是根节点,那么为什么不直接请求根节点呢?
然而,如果您真的想要使用XPath,您可以从XmlDocument
中的名称表中创建一个新的XmlNamespaceManager
,注册一个前缀,然后在名称空间管理器中传递给SelectSingleNode
过载,该过载需要一个。
在这个答案中有一些示例代码,但我再次强烈建议你考虑其他方法,如果你可以…特别是使用LINQ to XML,其中搜索(例如)所有"env:Body"元素(这里只有一个,但是…)将看起来像这样:
XNamespace env = "http://schemas.xmlsoap.org/soap/envelope/";
var bodies = doc.Descendants(env + "Body");