简体   繁体   English

在编码方面以XML格式化特定C#类的最简单方法

[英]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. 我正在尝试将类的一部分从C#模型序列化为XML文件。 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 我目前有这个:一个具有很多属性的类(其中一些用[XmlIgnore注释])来序列化

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 Name是我的c#模型中的属性

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 : 试试这个:将属性反映到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 . 最简单的方法是实现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. 有一个很好的教程如何在代码项目上执行此操作: 如何自定义XML序列化 ,但大多数代码您将不得不自己处理。 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 ) 我通常使用XmlSerializerMSDN XmlSerializer类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM