简体   繁体   中英

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.

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

您可以在报表类上实现IXmlSerializable接口,并覆盖ReadXml和WriteXml方法。

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM