2014-02-09 60 views
0

我有下面的C#代碼:我可以序列列表元素爲XML元素,而不是作爲XML屬性

[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> 

因此,列表元素序列化作爲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> 

回答

0

可以序列objs列表與自定義項目名稱爲不同類型的對象列表(你應該刪除您XmlInclude屬性)的XML數組:

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> 
+1

非常感謝。它解決了我所有的困擾 – user3282758