对象的序列化(用包含complextype的xsd创建)返回complextype作为元素
本文关键字:complextype 返回 元素 创建 xsd 包含 对象 序列化 | 更新日期: 2023-09-27 18:04:42
我有一个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元素,我如何防止这种情况发生?
找到了!我必须像这样在Example1类上添加一个额外的属性:
[XmlElement("Example2")]
public List<Example2Type> Example2
{
get
{
return this.example2Field;
}
set
{
this.example2Field = value;
}
}