简体   繁体   中英

Serialize Object using System.Xml.Serialization?

I have a class which is serialized to XML. This class has an Object member variable. How can I properly serialize this item? Obviously, it should be written as a string, but when read, it should become any type.

public class MyClass
{
    public MyClass()
        : this("", null)
    {
    }

    public MyClass(String name, Object value)
    {
        Name = name;
        Value = value;
    }

    [XmlAttribute("name")]
    public String Name;

    [XmlAttribute("value")] // Won't work!
    public Object Value;
}

Edit: Interestingly, [XmlElement()] is able to serialize the Object type. Thus, one workaround is to use a value instead of an attribute.

You can't serialize an Object as attribute - that would mean you'd have to serialize a (possibly) complex object into a string.

As XmlAttributeAttribute docs state:

You can assign the XmlAttributeAttribute only to public fields or public properties that return a value (or array of values) that can be mapped to one of the XML Schema definition language (XSD) simple types (including all built-in datatypes derived from the XSD anySimpleType type). The possible types include any that can be mapped to the XSD simple types, including Guid, Char, and enumerations. See the DataType property for a list of XSD types and how they are mapped to.NET data types.

You cannot serialize xmlattribute to an object. Either you have to ignore it by using [XmlIgnore] or load it as string using [XmlAttribute("value", typeof(string)] and convert it to whatever type in the post object construction.

You can do this (but de-serializing obviously wont work because of the object type):

private object m_object = null;

[XmlAttribute("value")]
public string ObjectValue
{
get { return m_object.ToString();}
set { m_object = value;}
}

[XmlIgnore]
public object Value
{
get { return m_object; }
set { m_object = value; }
}

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