So I have a class. I want to make it serializable (into XML and back). I know how to use Xml.Linq to serialize.. but it is serialization via hand - not automated alike protobuf with its [ProtoContract]
and other attributes when I mark up class and get it back and forward serializable.
所以我有一个班。我想使它可序列化(转换为XML和反XML)。我知道如何使用Xml。Linq序列化。但它是通过手工进行序列化的,而不是像protobuf那样使用它的[ProtoContract]和其他属性,当我标记类并让它返回并转发serializable时。
So I wonder ho waving
所以我不知道何朝我招手
public class Entries {
public List<Entry> Entries {get; set;}
}
public class Entry {
public string Id {get; set;}
public string Path {get; set;}
}
get XML like:
XML:
<entries>
<entry id="value" path="value"/>
</entries>
So how to mark up C# class with attributes to make it XML serializable?
那么如何用属性标记c#类以使其可序列化呢?
2 个解决方案
#1
2
You need to use attributes like [XmlRoot]
and [XmlAttribute]
for this. You can specify the XML element names as a parameter on the attributes.
为此需要使用[XmlRoot]和[XmlAttribute]等属性。可以将XML元素名称指定为属性上的参数。
See http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx and the rest of the attributes in the namespace for the attributes you can use.
请参阅http://msdn.microsoft.com/en- us/library/system.xml.serializ.xmlroot.xmlrootattribute.aspx和名称空间中其他属性,以获取可以使用的属性。
#2
2
You need to add attributes to the class and class members that match your XML, for example: -
您需要向与您的XML匹配的类和类成员添加属性,例如:-
[Serializable]
[XmlRoot("RootNode")]
public class Example
{
[XmlElement("Foo")]
public string Foo { get; set; }
[XmlElement("Bar")]
public string Bar { get; set; }
}
#1
2
You need to use attributes like [XmlRoot]
and [XmlAttribute]
for this. You can specify the XML element names as a parameter on the attributes.
为此需要使用[XmlRoot]和[XmlAttribute]等属性。可以将XML元素名称指定为属性上的参数。
See http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx and the rest of the attributes in the namespace for the attributes you can use.
请参阅http://msdn.microsoft.com/en- us/library/system.xml.serializ.xmlroot.xmlrootattribute.aspx和名称空间中其他属性,以获取可以使用的属性。
#2
2
You need to add attributes to the class and class members that match your XML, for example: -
您需要向与您的XML匹配的类和类成员添加属性,例如:-
[Serializable]
[XmlRoot("RootNode")]
public class Example
{
[XmlElement("Foo")]
public string Foo { get; set; }
[XmlElement("Bar")]
public string Bar { get; set; }
}