The easiest way to serialize a specific C # class to XML in terms of coding

I am trying to serialize part of a class from a C # model to an XML file. However, I would like to do this with less code.

I currently have this: a class with many properties (some of them are annotated using [XmlIgnore]) for serialization

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

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

a template that must fit

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

The name is a property in my C # model

The only thing I have found so far requires me to create another class for this, and I do not want to separate my model in different subclasses. Do you know a way (possibly with annotations) to create serialization for it?

+3
source share
3 answers

Try this: reflection of properties before 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))
        );
}
+2

- IXmlSerializable. , : XML, . , , .

0

I usually use XmlSerializer( MSML 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
}

Serialization:

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

All Articles