C# XML 反序列化错误:命名空间前缀“xsd”没有定义
我试图反序列化从 SOAP 响应收到的 XML 元素,但收到“命名空间前缀 'xsd' 未定义”错误。对此可能的解决方案是什么?
这是我得到的示例响应 XML:
<ns0:response xmlns:ns0="http://sample.site.com">
<ns0:additionalData>
<ns0:entry>
<ns0:key xsi:type="xsd:string">Test Key</ns0:key>
<ns0:value xsi:type="xsd:string">1</ns0:value>
</ns0:entry>
<ns0:entry>
<ns0:key xsi:type="xsd:string">Test Code</ns0:key>
<ns0:value xsi:type="xsd:string">1</ns0:value>
</ns0:entry>
</ns0:additionalData>
<ns0:mpiData>
<ns1:authenticationResponse xmlns:ns1="http://sample.site2.com">Y</ns1:authenticationResponse>
</ns0:mpiData>
</ns0:response>
我用这种方式反序列化它:
XDocument xDocument = XDocument.Parse(responseText);
var responseElement = xDocument.Descendants().Where(a => a.Name.LocalName == response.ElementName).Select(a => a).Last();
TResponse response = default(TResponse);
Stream memoryStream = new MemoryStream();
responseElement.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
var serializer = new XmlSerializer(typeof(TResponse));
using (XmlReader xmlReader = XmlReader.Create(memoryStream))
{
response = (TResponse)serializer.Deserialize(xmlReader);
}
return response;
I am trying to deserialize an XML element that I received from a SOAP response, but I am getting the "Namespace prefix 'xsd' is not defined" error. What's the possible solution for this?
Here's the sample response XML I'm getting:
<ns0:response xmlns:ns0="http://sample.site.com">
<ns0:additionalData>
<ns0:entry>
<ns0:key xsi:type="xsd:string">Test Key</ns0:key>
<ns0:value xsi:type="xsd:string">1</ns0:value>
</ns0:entry>
<ns0:entry>
<ns0:key xsi:type="xsd:string">Test Code</ns0:key>
<ns0:value xsi:type="xsd:string">1</ns0:value>
</ns0:entry>
</ns0:additionalData>
<ns0:mpiData>
<ns1:authenticationResponse xmlns:ns1="http://sample.site2.com">Y</ns1:authenticationResponse>
</ns0:mpiData>
</ns0:response>
I'm deserializing it this way:
XDocument xDocument = XDocument.Parse(responseText);
var responseElement = xDocument.Descendants().Where(a => a.Name.LocalName == response.ElementName).Select(a => a).Last();
TResponse response = default(TResponse);
Stream memoryStream = new MemoryStream();
responseElement.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
var serializer = new XmlSerializer(typeof(TResponse));
using (XmlReader xmlReader = XmlReader.Create(memoryStream))
{
response = (TResponse)serializer.Deserialize(xmlReader);
}
return response;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为 XML 缺少这一行
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
I think the XML is missing this line
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
添加来声明 xsd 命名空间前缀
通过在使用 xsd 的元素或其上方
。例如,将其添加到
ns0:response
元素中,该元素对于所有可能需要它的地方都是通用的:Declare the
xsd
namespace prefix by addingat or above the element on which it's used.
For example, add it to the
ns0:response
element, which is common to all likely places it will be needed: