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

Arm*_*rat 1 c# xml serialization

假设我有以下内容:

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想序列化为XML:

<Foo>
    <barId>123</barId>
    <ramId>234</ramId>
</Foo>
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

我想我必须创建一个序列化的中间类.备择方案?

Nic*_*rey 9

你的意思是这样的?

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

  }

}
Run Code Online (Sandbox Code Playgroud)