[英]Serialize Object using System.Xml.Serialization?
I have a class which is serialized to XML. 我有一个序列化为XML的类。 This class has an
Object
member variable. 此类具有一个
Object
成员变量。 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. 编辑:有趣的是,
[XmlElement()]
能够序列化Object
类型。 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: 作为XmlAttributeAttribute文档状态:
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).
您只能将XmlAttributeAttribute分配给返回可以映射到XML架构定义语言(XSD)简单类型之一(包括从XSD派生的所有内置数据类型)的值(或值数组)的公共字段或公共属性。 anySimpleType类型)。 The possible types include any that can be mapped to the XSD simple types, including Guid, Char, and enumerations.
可能的类型包括可以映射到XSD简单类型的任何类型,包括Guid,Char和枚举。 See the DataType property for a list of XSD types and how they are mapped to.NET data types.
有关XSD类型及其如何映射到.NET数据类型的列表,请参见DataType属性。
You cannot serialize xmlattribute to an object. 您不能将xmlattribute序列化为对象。 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. 您必须使用
[XmlIgnore]
忽略它,或者使用[XmlAttribute("value", typeof(string)]
将其加载为字符串[XmlAttribute("value", typeof(string)]
然后将其转换为post对象构造中的任何类型。
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.