XmlSerializer / StreamWriter将多个类型/类放入同一个xml文件中

时间:2016-01-14 10:38:17

标签: c# .net xml xsd xmlserializer

我想根据架构(XSD)创建XML文件。我在StackOverflow上发现了这个问题:Generating XML file using XSD file

它适用于这样的简单示例:

var data = new ProfileType();
data.Name = "Test";
data.Address = "Street";

var serializer = new XmlSerializer(typeof(ProfileType));
using (var stream = new StreamWriter("D:\\test.xml")) serializer.Serialize(stream, data);

但是如何在同一个xml文件中添加更多类/类型呢?如果我在下面添加这些代码行,它们将覆盖text.xml文件:

var data2 = new MemberType();
data2.Age = "25";
data2.Code = "Z14x";
data2.Color = "Red":

var serializer2 = new XmlSerializer(typeof(MemberType));
using (var stream = new StreamWriter("D:\\test.xml")) serializer2.Serialize(stream, data2);

1 个答案:

答案 0 :(得分:2)

您可以序列化对象列表:

示例:

public class Type1
{
    public string Name { get; set; }
    public Type1() { }
}

public class Type2
{
    public string Name { get; set; }
    public Type2() { }
}

//....

List<object> list = new List<object>();
list.Add(new Type1() { Name = "Name1" });
list.Add(new Type2() { Name = "Name2" });

 XmlSerializer serializer = new XmlSerializer(typeof(List<object>), new Type[] { typeof(Type1), typeof(Type2) });
 using (TextWriter writer = new StreamWriter("result.xml"))
 {
     serializer.Serialize(writer, list);
 }

结果:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <anyType xsi:type="Type1">
    <Name>Name1</Name>
  </anyType>
  <anyType xsi:type="Type2">
    <Name>Name2</Name>
  </anyType>
</ArrayOfAnyType>