0

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.

1
  • 4
    What does "Won't work!" mean, exactly? What "Won't work!"? Exceptions? Incorrect deserialization? Something else? Commented Apr 18, 2012 at 15:09

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Will look this up and decide what to do.
Usually you'd simply serialize the Object as XML element, here's some discussion on how to customize this serialization
2

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.

1 Comment

When you say "converting", do you mean parsing the string value?
1

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

1 Comment

I suppose I could try parsing the string in the setter and assign it accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.