如何从这个c#类创建XML文件?

时间:2014-08-13 19:52:59

标签: c# xml

我想从以下c#类创建一个XML文件,反之亦然。我怎么能这样做?

public class Settings
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Value { get; set; }

    public string ParentId { get; set; }

    public List<Settings> SubSettings { get; set; }

    public bool IsRoot
    {
        get
        {
            return string.IsNullOrEmpty(ParentId);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用XmlSerializer在C#中序列化类,如下所示:

var s = new Settings()
{
    Id = "id",
    Name = "name",
    ParentId = "parentId",
    Value = "value",
    SubSettings = new List<Settings>()
    {
        new Settings() 
        { 
            Id = "subId", 
            Name = "subName", 
            ParentId = "subParentId", 
            Value = "subValue", 
            SubSettings = new List<Settings>() 
        }
    }
};

XmlSerializer serializer = new XmlSerializer(typeof(Settings));

string fileName = "C:\\test.xml";

using (FileStream fs = File.Open(fileName, FileMode.CreateNew))
{
    serializer.Serialize(fs, s);
}

这是我得到的结果:

<?xml version="1.0"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>id</Id>
  <Name>name</Name>
  <Value>value</Value>
  <ParentId>parentId</ParentId>
  <SubSettings>
    <Settings>
      <Id>subId</Id>
      <Name>subName</Name>
      <Value>subValue</Value>
      <ParentId>subParentId</ParentId>
      <SubSettings />
    </Settings>
  </SubSettings>
</Settings>

然后,您可以将其反序列化为这样的对象:

XmlSerializer serializer = new XmlSerializer(typeof(Settings));

Stream fs = new FileStream("C:\\test.xml", FileMode.Open);

Settings settings = (Settings)serializer.Deserialize(fs);