我一直在使用 C# 处理 SOAP 请求/响应。我知道请求和响应的格式应该如何。我已经成功创建了[WebMethod]
发送请求,我可以检索 XML
从中得到回应。问题是我得到的响应看起来像这样
<soapenv:Header>
<v1:ResultStatus xmlns:v1="http://group.com/contract/vho/header/v1">
<bf:Timestamp xmlns:bf="http://docs.oasis-open.org/wsrf/bf-2">27-Nov-17 1:42:24 PM</bf:Timestamp>
<bf:ErrorCode xmlns:bf="http://docs.oasis-open.org/wsrf/bf-2">OK</bf:ErrorCode>
<bf:Description xmlns:bf="http://docs.oasis-open.org/wsrf/bf-2">Integration Id cannot be retrieved for this user</bf:Description>
<v11:Message xmlns:v11="http://group.com/schema/common/v1">FAILURE</v11:Message>
</v1:ResultStatus>
</soapenv:Header>
<SOAP-ENV:Body xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<v1:CheckAuthenticationCredentialVBMResponse xmlns:v1="http://group.com/schema/vbm/identity/authentication-credential/v1">
<v1:AuthenticationCredentialVBO actionCode="ADD">
<v11:IDs xmlns:v11="http://group.com/schema/common/v1">
<v11:ID schemeName="Authentication Credential ID">5535</v11:ID>
</v11:IDs>
</v1:CheckAuthenticationCredentialVBMResponse>
</SOAP-ENV:Body>
当我尝试使用 XmlDocument xmldoc.GetElementsByTagName("bf:ErrorCode");
来阅读它时或XmlDocument xmldoc.GetElementsByTagName("v11:Message");
它认为:
作为特殊字符,因此无法继续执行,抛出此异常:
The ':' character, hexadecimal value 0x3A, cannot be included in a name.
我试图找到一些关于此的文档,但我似乎找不到类似的东西。有人可以帮忙吗?
如果需要更多信息,请发表评论。
最佳答案
bf:ErrorCode
是前缀 bf
指示的命名空间中的 xml 元素 ErrorCode
。您可以在声明中看到此前缀代表什么 namespace :
xmlns:bf="http://docs.oasis-open.org/wsrf/bf-2"
所以 bf:ErrorCode
是命名空间 http://docs.oasis-open.org/wsrf/bf-2
中的元素 ErrorCode
。请注意,前缀名称(“bf”)无关紧要,重要的是命名空间本身(“http://docs.oasis-open.org/wsrf/bf-2”)。因此,您不应该按 namespace 前缀搜索元素,因为它可能随时更改,而不会更改 xml 文档的含义。您应该只按命名空间搜索。
有了这些知识,你就可以获得这样的元素:
string targetNamespace = "http://docs.oasis-open.org/wsrf/bf-2";
var elements = doc.GetElementsByTagName("ErrorCode", targetNamespace);
请注意,GetElementsByTagName
的文档建议不要使用此方法,而应使用 SelectNodes
。您可以对 SelectNodes
执行相同的操作,如下所示:
var doc = new XmlDocument();
doc.LoadXml(xml);
var nsManager = new XmlNamespaceManager(doc.NameTable);
// note that prefix doesn't _need_ to be "bf"
// (though it could be "bf" if you wish)
nsManager.AddNamespace("anyPrefixHere", "http://docs.oasis-open.org/wsrf/bf-2");
// use the same prefix here you used in `AddNamespace` call above
var elements = doc.SelectNodes("//anyPrefixHere:ErrorCode", nsManager);
关于c# - 由于特殊字符而难以读取 SOAP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511540/