我有一个看起来像这样的 XSD:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Example1">
<xs:complexType>
<xs:sequence>
<xs:element name="Example2" type="Example2Type" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="Example2Type">
<xs:sequence>
<xs:element name="Field1" type="xs:int"/>
<xs:element name="Field2" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
使用 VS2010,我把这个 XSD 变成了一个如下所示的类:
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Collections.Generic;
public partial class Example1
{
private List<Example2Type> example2Field;
public Example1()
{
this.example2Field = new List<Example2Type>();
}
public List<Example2Type> Example2
{
get
{
return this.example2Field;
}
set
{
this.example2Field = value;
}
}
}
public partial class Example2Type
{
private int field1Field;
private int field2Field;
public int Field1
{
get
{
return this.field1Field;
}
set
{
this.field1Field = value;
}
}
public int Field2
{
get
{
return this.field2Field;
}
set
{
this.field2Field = value;
}
}
}
我现在想使用上述类创建一些对象。我使用以下代码执行此操作:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Example1 test = new Example1();
test.Example2 = new List<Example2Type>();
test.Example2.Add(new Example2Type());
test.Example2[0].Field1 = 2;
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(test.GetType());
x.Serialize(Console.Out, test);
Console.ReadLine();
}
}
}
现在生成的 XML 看起来与我预期的不同。它现在看起来像这样:
<Example1>
<Example2>
<Example2Type>
<Field1></Field1>
<Field2></Field2>
</Example2Type>
</Example2>
</Example1>
为什么在此处添加 Example2Type 元素,如何防止这种情况发生?