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

本文关键字:一个 文件 XML 创建 | 更新日期: 2023-09-27 18:17:57

我想从下面的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);
        }
    }
}

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

您可以使用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);