开发者

XML Serialization of an ENUM is empty

开发者 https://www.devze.com 2023-03-17 15:56 出处:网络
This is the Enum generated by the XSD开发者_C百科 [System.CodeDom.Compiler.GeneratedCodeAttribute(\"xsd\", \"2.0.50727.42\")]

This is the Enum generated by the XSD

开发者_C百科
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/Utenza.xsd")]
public enum MeterType {

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("a diffalco")]
    adiffalco,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("con diffalco")]
    condiffalco,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("di riserva")]
    diriserva,
}

and.. this is the code i use to serialize

String XmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(Tipo);

XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);           
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlString = UTF8ByteArrayToString(memoryStream.ToArray());

the XML output does not contain the attribute rappresenting the value of the Enum. Can someone help? Thanks a lot.


Your question helped me solve a problem that I was having with enums close to 10 years later. You probably figured out the answer by now. You need to have an enum value for NULL which would be the first value in the enum (0). Then use:

[System.Xml.Serialization.XmlEnumAttribute("")] 

as the attribute used for the "Null" enum value. This is needed for when the XmlSerialzer encounters the value null or empty string for an XML element that needs tp map to the enum.

I hope this answer helps anyone with a similar problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号