[英]Xml Deserialization Fails on Empty Element
I have an Xml document that looks similar too 我有一个看起来相似的Xml文档
<Reports xmlns="">
<Report>
<ReportID>1</ReportID>
<ParameterTemplate />
</Report>
</Reports>
It fails serializing to this object 它无法序列化到此对象
[XmlType(TypeName = "Report")]
public class Report
{
[XmlElement("ReportID")]
public int ID { get; set; }
[XmlElement("ParameterTemplate")]
public XElement ParameterTemplate { get; set; }
}
It's failing because the empty ParameterTemplate element, because if it contains child elements it deserializes fine. 它失败了,因为空的ParameterTemplate元素,因为如果它包含子元素,它反序列化很好。
How can I get this to work? 我怎样才能让它发挥作用?
This is my Deserialization Code 这是我的反序列化代码
var serializer = new XmlSerializer(typeof(Report));
return (Report)serializer.Deserialize(source.CreateReader());
The exception is 例外是
The XmlReader must be on a node of type Element instead of a node of type EndElement. XmlReader必须位于Element类型的节点上,而不是EndElement类型的节点。
How can I get this to deserialize with the existing xml? 如何使用现有的xml进行反序列化?
Thanks -c 谢谢-c
It looks like the content of XElement
- if not null - cannot be an empty XML element. 看起来XElement
的内容 - 如果不是 null - 不能是一个空的XML元素。 In other words, you would not be able to serialize that XML in your example from an in-memory representation/instance of your Report
class. 换句话说,您将无法从您的Report
类的内存表示/实例序列化示例中的 XML。
I created the following method to patch the XML text: 我创建了以下方法来修补XML文本:
Public Function XMLReaderPatch(rawXML As String) As String
If String.IsNullOrEmpty(rawXML) Then Return rawXML
'Pattern for finding items similar to <name*/> where * may represent whitespace followed by text and/or whitespace
Dim pattern As String = "<(\S+)(\s[^<|>]*)?/>"
'Pattern for replacing with items similar to <name*></name> where * may represent whitespace followed by text and/or whitespace
Dim replacement As String = "<$1$2></$1>"
Dim rgx As New Text.RegularExpressions.Regex(pattern)
Return rgx.Replace(rawXML, replacement)
End Function
您可以在报表类上实现IXmlSerializable
接口,并覆盖ReadXml和WriteXml方法。
Use IsNullable=True 使用IsNullable = True
[XmlType(TypeName = "Report")]
public class Report
{
[XmlElement("ReportID")]
public int ID { get; set; }
[XmlElement("ParameterTemplate", IsNullable=true)]
public XElement ParameterTemplate { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.