gpt4 book ai didi

c# - 如何使用.NET XML序列化将对象序列化为单个值

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:17 27 4
gpt4 key购买 nike

假设我有以下内容:

[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;
}

}

}

关于c# - 如何使用.NET XML序列化将对象序列化为单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724075/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com