将类列表序列化为XML

Jon*_*tus 34 c# xml serialization

我有一组类,我想序列化为XML文件.它看起来像这样:

public class Foo
{
  public List<Bar> BarList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

bar只是一组属性的包装器,如下所示:

public class Bar
{
  public string Property1 { get; set; }
  public string Property2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想对此进行标记,以便将其输出到XML文件 - 这将用于持久性,并且还可以通过XSLT将设置呈现为一个很好的人类可读形式.

我想得到一个像这样的好的XML表示:

<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <BarList>
    <Bar>
      <Property1>Value</Property1>
      <Property2>Value</Property2>   
    </Bar>
    <Bar>
      <Property1>Value</Property1>
      <Property2>Value</Property2>   
    </Bar>
  </Barlist>
</Foo>
Run Code Online (Sandbox Code Playgroud)

Barlist中的所有条形图都写在哪里,包含所有属性.我很确定我需要在类定义上使用一些标记才能使它工作,但我似乎找不到合适的组合.

我用属性标记了Foo

[XmlRoot("Foo")]  
Run Code Online (Sandbox Code Playgroud)

list<Bar>属性

[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")]
Run Code Online (Sandbox Code Playgroud)

试图告诉Serializer我想要发生什么.这似乎不起作用,我只是得到一个空标记,看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<Foo> 
  <Barlist />
</Foo>
Run Code Online (Sandbox Code Playgroud)

我不确定我使用自动属性的事实是否会产生任何影响,或者如果使用泛型需要任何特殊处理.我已经使用了更简单的类型,比如字符串列表,但到目前为止,我已经找到了一个类列表.

Car*_*arl 31

要检查一下,您是否将Bar标记为[Serializable]?

此外,您需要Bar上的无参数ctor来反序列化

嗯,我用过:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        Foo f = new Foo();

        f.BarList = new List<Bar>();

        f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" });

        XmlSerializer ser = new XmlSerializer(typeof(Foo));

        using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create))
        {
            ser.Serialize(fs, f);
        }
    }
}

public class Foo
{
    [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
    public List<Bar> BarList { get; set; }
}

[XmlRoot("Foo")]
public class Bar
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这产生了:

<?xml version="1.0"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BarList>
    <Bar>
      <Property1>abc</Property1>
      <Property2>def</Property2>
    </Bar>
  </BarList>
</Foo>
Run Code Online (Sandbox Code Playgroud)

  • XML Serializer不使用`[Serializable]`. (6认同)