我可以将列表元素序列化为XML元素而不是XML属性

时间:2014-02-09 15:54:21

标签: c# xml-serialization

我有以下C#代码:

    [Serializable][XmlInclude(typeof(TypeDefnType1))][XmlInclude(typeof(TypeDefnType2))]
public class TypeDefn
{
    [XmlElementAttribute("Z-ONE")]
    public int Z1;
    [XmlAttributeAttribute("IDENTIFIER")]
    public string id;
    public TypeDefn() { Z1 = 10; id = "IIIIDDDD" + Z1; }        
}
[Serializable]
public class TypeDefnType1 : TypeDefn
{
    [XmlElementAttribute("TYPE-ONE")]
    public int type1;
}
[Serializable]
public class TypeDefnType2 : TypeDefn 
{
    [XmlElementAttribute("TYPE-TWO")]
    public int type2;
}
[Serializable]
public class ContainsArr {
    [XmlElementAttribute("DATATYPES")]
    public List<TypeDefn> objs ;        
}
class Program
{
    static void Main(string[] args)
    {
            ContainsArr obj = new ContainsArr() ;
            obj.objs = new List<TypeDefn>();
            obj.objs.Add(new TypeDefnType1());
            obj.objs.Add(new TypeDefnType2());

            TextWriter write = new StreamWriter("MyNewClass.xml");

            XmlSerializer ser = new XmlSerializer(typeof(ContainsArr));
            ser.Serialize(write, obj);
    }
}

这将生成以下xml文件:

<?xml version="1.0" encoding="utf-8"?>
<ContainsArr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DATATYPES xsi:type="TypeDefnType1" IDENTIFIER="IIIIDDDD10">
    <Z-ONE>10</Z-ONE>
   <TYPE-ONE>0</TYPE-ONE>
</DATATYPES>
<DATATYPES xsi:type="TypeDefnType2" IDENTIFIER="IIIIDDDD10">
    <Z-ONE>10</Z-ONE>
    <TYPE-TWO>0</TYPE-TWO>
 </DATATYPES>
</ContainsArr>

因此,List元素被序列化为DATATYPE的属性。 我想要的是这些元素显示为DATATYPE的元素。 所以我希望生成以下文件:

<?xml version="1.0" encoding="utf-8"?>
<ContainsArr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <DATATYPEs>
        <TypeDefnType1 IDENTIFIER="IIIIDDDD10">
            <Z-ONE>10</Z-ONE>
            <TYPE-ONE>0</TYPE-ONE>
        </TypeDefnType1>
    </DATATYPES>
    <DATATYPES>
        <TypeDefnType2 IDENTIFIER="IIIIDDDD10">
            <Z-ONE>10</Z-ONE>
            <TYPE-TWO>0</TYPE-TWO>
        </TypeDefnType2>
    </DATATYPES>

1 个答案:

答案 0 :(得分:0)

您可以将objs列表序列化为XML数组,其中包含列表中不同类型对象的自定义项名称(您应删除XmlInclude属性):

public class ContainsArr
{
    [XmlArray("DATATYPES")]
    [XmlArrayItem("TypeDefnType1", Type = typeof(TypeDefnType1))]
    [XmlArrayItem("TypeDefnType2", Type = typeof(TypeDefnType2))]
    public List<TypeDefn> objs;
}

这将为以下xml提供指定的元素名称而不是attibutes:

<?xml version="1.0"?>
<ContainsArr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DATATYPES>
    <TypeDefnType1 IDENTIFIER="IIIIDDDD10">
      <Z-ONE>10</Z-ONE>
      <TYPE-ONE>0</TYPE-ONE>
    </TypeDefnType1>
    <TypeDefnType2 IDENTIFIER="IIIIDDDD10">
      <Z-ONE>10</Z-ONE>
      <TYPE-TWO>0</TYPE-TWO>
    </TypeDefnType2>
  </DATATYPES>
</ContainsArr>