Xml Deserialization Fails on Empty Element
I have an Xml document that looks similar too
<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.
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.
How can I get this to deserialize with the existing xml?
Thanks -c
It looks like the content of XElement
- if not null - cannot be an empty XML element. 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.
You can implement IXmlSerializable
interface on your report class and overwrite ReadXml and WriteXml methods.
I created the following method to patch the XML text:
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
Use IsNullable=True
[XmlType(TypeName = "Report")]
public class Report
{
[XmlElement("ReportID")]
public int ID { get; set; }
[XmlElement("ParameterTemplate", IsNullable=true)]
public XElement ParameterTemplate { get; set; }
}
精彩评论