[英]XML serialization issue in C#
我正在开展一个项目,我们正在从遗留代码迁移到新的 .net 核心代码。 在 xml 序列化过程中遇到问题。
这是旧应用程序中显示的内容:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Response xmlns="http://example.com/WebServices/">
<Type i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
<UserId i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
</Response>
</s:Body>
</s:Envelope>
并在新代码中:
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Response xmlns="http://example.com/WebServices/">
<xsi:Type>PROCESSED</xsi:Type>
<xsi:UserId />
</Response>
</s:Body>
</s:Envelope>
这是 class 定义:
[XmlType(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class AResponse
{
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public ABody body { get; set; }
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
public AResponse()
{
xmlns.Add("s", "http://schemas.xmlsoap.org/soap/envelope/");
}
}
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class ABody
{
[XmlElement(ElementName = "OAuthResponse", Namespace = "http://example.com/WebServices/")]
public Response result { get; set; }
}
[XmlRoot(ElementName = "OAuthResponse", Namespace = "http://example.com/WebServices/")]
public class Response
{
[XmlElement(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = true)]
public string Type { get; set; }
[XmlElement(IsNullable = true, ElementName = "UserId", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string UserId { get; set; } = "";
}
如果您注意到显示新旧 xml 之间的差异,则新代码会自动添加 xsi 标记并将命名空间置于 header 级别,我所做的任何更改都不会更改它。 你能建议如何使这项工作?
要删除 Type 和 UserId 元素中的“xsi:”,只需从 XmlElementAtttribute 中删除Namespace = "http://www.w3.org/2001/XMLSchema-instance"
,例如
[XmlElement(IsNullable = true)]
public string Type { get; set; }
[XmlElement(IsNullable = true)]
public string UserId { get; set; };
IsNullable = true
应该保留,它使UserId = null
被序列化为<UserId xsi:nil="true" />
; UserId = ""
将被序列化为<UserId />
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.