![](/img/trans.png)
[英]Is there a way to serialize a c# class to xml without put attributes on the class?
[英]Simplest way to serialize a particular C# class in XML in terms of coding
我正在嘗試將類的一部分從C#模型序列化為XML文件。 但是我想用盡可能少的代碼來做。
我目前有這個:一個具有很多屬性的類(其中一些用[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;}
...
}
我需要匹配的模式
<Properties>
<Property Name="id">Value</Property>
<Property Name="Title">Value</Property>
<Property Name="Body">Value</Property>
...
</Properties>
Name是我的c#模型中的屬性
到目前為止我發現的唯一的東西需要我為它創建一個不同的類,我不想在不同的子類中分割我的模型。 您是否知道為此創建自定義序列化的方法(可能帶有注釋)?
試試這個:將屬性反映到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))
);
}
最簡單的方法是實現IXmlSerializable 。 有一個很好的教程如何在代碼項目上執行此操作: 如何自定義XML序列化 ,但大多數代碼您將不得不自己處理。 如果可能,我建議您使用標准序列化,這樣做更容易。
我通常使用XmlSerializer
( MSDN XmlSerializer類 )
反序列化:
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
}
連載:
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.