是否可以在类 XMLTypeAttribute 中有两个命名空间来处理 2 个 SOAP 响应的反序列化?



>我有一个具有以下声明的类:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
public partial class Envelope
{
private EnvelopeBody bodyField;
/// <remarks/>
public EnvelopeBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
.
. another code generated here based on response XML...
.
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "order")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "order", IsNullable = false)]
public partial class insertResponse
{
private insertResponseOut outField;
/// <remarks/>
public insertResponseOut @out
{
get
{
return this.outField;
}
set
{
this.outField = value;
}
}
}

在反序列化包含<insertResponse xmlns="order">的响应XML时,我可以成功地做到这一点。

我有另一个XML SOAP响应,它格式完全相同,我想使用相同的类,但XmlTypeAttribute不同:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "customer")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "customer", IsNullable = false)]
public partial class insertResponse
{
private insertResponseOut outField;
/// <remarks/>
public insertResponseOut @out
{
get
{
return this.outField;
}
set
{
this.outField = value;
}
}
}

目前我有一个处理 SOAP 响应反序列化的方法:

private Envelope DeserializeSoapResponse<T>(string soapResponse)
{
var serealizer = new XmlSerializer(typeof(T));
Envelope result;
using (TextReader reader = new StringReader(soapResponse))
{
result = (Envelope)serealizer.Deserialize(reader);
}
return result;
}

soapResponse 参数不是 XML 的路径,它是一个字符串,表示来自服务器的 xml SOAP 响应。

我还尝试使用自定义xml阅读器:

public class CustomXmlReader: System.Xml.XmlTextReader
{
public CustomXmlReader(string url) : base(url) { }
public override string NamespaceURI
{
get
{
if (base.NamespaceURI == "order")
return "customer";
return base.NamespaceURI;
}
}
}

正如建议的那样,但我有以下错误:illegal character in path,因为正如我所期望的那样,我需要将 URL 发送到 SOAP 响应,但发送字符串

我怎么能做这样的事情?是否可以为XmlTypeAttributeXmlRootAttribute定义多个命名空间

为此,您可以使用自定义 xml 读取器。

public class CustomXmlReader : XmlTextReader
{
// Define other required constructors
public CustomXmlReader(string url) : base(url) { }
public CustomXmlReader(TextReader reader) : base(reader) { }
public override string NamespaceURI
{
get
{
if (base.NamespaceURI == "order")
return "customer";
return base.NamespaceURI;
}
}
}

它会动态将order命名空间转换为customer命名空间。

因此,您的类应该只有一个customernamepase 声明:

[XmlType(AnonymousType = true, Namespace = "customer")]
[XmlRoot(Namespace = "customer", IsNullable = false)]
public partial class insertResponse

照常使用:

string xml = "your xml here";
insertResponse response;
using (var stringReader = new StringReader(xml))
using (var xmlReader = new CustomXmlReader(stringReader))
response = (insertResponse)xs.Deserialize(xmlReader);

最新更新