简体   繁体   中英

Simplest way to serialize a particular C# class in XML in terms of coding

I'm trying to serialize a part of a class from a C# Model to a XML File. However i'd like to do it with the less possible amount of code.

I currently have this : a class with a lot of properties (some of them are annotated with [XmlIgnore]) to serialize

public class MyClass
{
    public int id {get;set;}
    public string Title {get;set;}
    public string Body {get;set;}

    [XmlIgnore]
    public byte[] Image {get;set;}
    ...
}

the pattern i need to match

<Properties>
<Property Name="id">Value</Property>
<Property Name="Title">Value</Property>
<Property Name="Body">Value</Property>
...
</Properties>

the Name is the property in my c# model

The only things i found so far needs me to create a different class for that, and i don' t want to split my model in different sub classes. Do you know a way (Maybe with annotations) to create a custom serialization for this ?

Try this: reflection of properties to XElement :

public static XElement ToXml<T>(T obj)
{
     return new XElement("Properties",
                         from pi in  typeof (T).GetProperties()
                         where !pi.GetIndexParameters().Any() 
                                && !pi.GetCustomAttributes(typeof(XmlIgnoreAttribute), false).Any()
                         select new XElement("Property"
                                             , new XAttribute("Name", pi.Name)
                                             , pi.GetValue(obj, null))
        );
}

The easiest way is to implement IXmlSerializable . There is a nice tutorial how to do this on code project: How to customize XML serialization , but most code you will have to handle yourself. If it is possible I will suggest you to use standard serialization it is much more easy to do.

I usually use XmlSerializer ( MSDN XmlSerializer Class )

Deserialize:

var ser = new XmlSerializer(typeof(MyType));

using (var fs = new FileStream("Resources/MyObjects.xml", FileMode.Open))
{
    var obj = ser.Deserialize(fs);
    var myObject = obj as myType;
    if(myObject != null)
        // do action
}

Serialize:

 var ser = new XmlSerializer(typeof(MyType));
 using (var fs = new FileStream("Resources/MyObjects.xml", FileMode.Create))
 {
     ser.Serialize(fs, myObject)
 }

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