试试看,
代码
类声明
[Serializable()]
[System.Xml.Serialization.XmlInclude(typeof(CUST_HOLD))]
[System.Xml.Serialization.XmlInclude(typeof(HOLD))]
[System.Xml.Serialization.XmlType(TypeName = "Data2")]
public class Root2
{
[System.Xml.Serialization.XmlArrayItem("CUST_HOLD")]
public CUST_HOLD[] CUST_HOLD;
[System.Xml.Serialization.XmlArrayItem("HOLD")]
public HOLD[] HOLD;
}
[Serializable()]
[System.Xml.Serialization.XmlType("CUST_HOLD")]
public class CUST_HOLD
{
public int i;
}
[Serializable()]
[System.Xml.Serialization.XmlType("HOLD")]
public class HOLD
{
public int i;
}
序列化
List<Root2> list = new List<Root2>();
Root2 obj = new Root2();
obj.CUST_HOLD = new CUST_HOLD[] { new CUST_HOLD() { i = 1 }, new CUST_HOLD() { i = 1 }, new CUST_HOLD() { i = 1 } };
obj.HOLD = new HOLD[] { new HOLD() { i = 1 }, new HOLD() { i = 1 }, new HOLD() { i = 1 } };
list.Add(obj);
//Serialize List<Root2>
System.Xml.Serialization.XmlSerializer Serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Root2>),new System.Xml.Serialization.XmlRootAttribute("Root2"));
System.IO.MemoryStream mo = new System.IO.MemoryStream();
Serializer.Serialize(mo, list);
string str = UnicodeEncoding.UTF8.GetString(mo.ToArray());
输出:
<?xml version="1.0"?>
<Root2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data2>
<CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
</CUST_HOLD>
<HOLD>
<HOLD>
<i>1</i>
</HOLD>
<HOLD>
<i>1</i>
</HOLD>
<HOLD>
<i>1</i>
</HOLD>
</HOLD>
</Data2>
</Root2>
反序列化
string str = @"<?xml version='1.0'?>
<Root2 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<Data2>
<CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
<CUST_HOLD>
<i>1</i>
</CUST_HOLD>
</CUST_HOLD>
<HOLD>
<HOLD>
<i>1</i>
</HOLD>
<HOLD>
<i>1</i>
</HOLD>
<HOLD>
<i>1</i>
</HOLD>
</HOLD>
</Data2>
</Root2>";
System.Xml.Serialization.XmlSerializer Serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Root2>), new System.Xml.Serialization.XmlRootAttribute("Root2"));
System.IO.MemoryStream mo = new System.IO.MemoryStream(UnicodeEncoding.UTF8.GetBytes(str));
List<Root2> list = (List<Root2>)Serializer .Deserialize(mo);
注意 <Data2>
标签仅在序列化类型List<Root2>
为单Root2
实例<Data2>
标签时才会出现在 xml 字符串中,并且无法进行反序列化。反序列化将为CUST_HOLD
&返回空值HOLD
。返回类型应该是List<Root2>
.