[英]How to serialize a class with a complex property using XML serialization in .NET?
[英]How to use .NET XML serialization to serialize an object to a single value
假設我有以下內容:
[Serializable]
public class Foo
{
public Bar bar
{
get;
set;
}
public Ram ram
{
get;
set;
}
}
[Serializable]
public class Bar
{
[XmlElement("barId")]
public int Id
{
get;
set;
}
}
[Serializable]
public class Ram
{
[XmlElement("ramId")]
public int RamId
{
get;
set;
}
}
我想序列化為XML為:
<Foo>
<barId>123</barId>
<ramId>234</ramId>
</Foo>
做這個的最好方式是什么?
我想我必須創建一個中間類來序列化。 備擇方案?
你的意思是這樣嗎?
using System.Text;
using System.Xml;
using System.Xml.Serialization ;
namespace ConsoleApplication11
{
[XmlRoot("Foo")]
public class Foo
{
public Foo()
{
bar = new Bar() ;
ram = new Ram() ;
}
[XmlElement("barId")]
public Bar bar { get; set; }
[XmlElement("ramId")]
public Ram ram { get; set; }
}
public class Bar
{
[XmlText]
public int Id { get; set; }
}
public class Ram
{
[XmlText]
public int RamId { get; set; }
}
class Program
{
static int Main( string[] argv )
{
XmlSerializer xml = new XmlSerializer( typeof(Foo) ) ;
XmlWriterSettings settings = new XmlWriterSettings() ;
settings.Indent = true ;
settings.IndentChars = " " ;
settings.Encoding = new UnicodeEncoding( false , false ) ; // little-endian, omit byte order mark
settings.OmitXmlDeclaration = true ;
Foo instance = new Foo() ;
instance.bar.Id = 1234 ;
instance.ram.RamId = 9876 ;
StringBuilder sb = new StringBuilder() ;
using ( XmlWriter writer = XmlWriter.Create( sb , settings ) )
{
xml.Serialize(writer, instance ) ;
}
string xmlDoc = sb.ToString() ;
Console.WriteLine(xmlDoc) ;
return 0;
}
}
}
使用XmlSerializer。 這個問題與您的問題相似,並且有一些有用的答案: 使用StringWriter進行XML序列化
我猜你可以做這樣的事情:
[Serializable]
public class Foo
{
private Bar _bar;
public int BarID
{
get { return _bar.Id;}
set
{
if (_bar==null) _bar= new Bar();
_bar.Id = id;
}
}
}
盡管我覺得我應該補充一點,這聽起來有些誤導...您為什么要這樣做?
將屬性標記為Bar和Ram以防止序列化,添加公開屬性以代替ID,如果Bar為null,則使BarId的get返回null,否則返回Bar.Id。 讓集合按ID加載現有的Bar或創建一個新的Bar(根據您的BL)。 Ram也一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.