2012-01-03 61 views
1
using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Diagnostics; 
using System.IO; 
using System.Xml; 
using System.Xml.Linq; 
using System.Xml.Serialization; 
using System.Linq; 

namespace Serialize 
{  
    public class Good 
    { 
     public int a; 
     public Good() {} 

     public Good(int x) 
     { 
      a = x; 
     } 
    } 

    public class Hello 
    { 
     public int x; 
     public List<Good> goods = new List<Good>(); 

     public Hello() 
     { 
      goods.Add(new Good(1)); 
      goods.Add(new Good(2)); 
     } 
    } 

    [XmlRootAttribute("Component", IsNullable = false)] 
    public class Component { 
     //[XmlElement("worlds_wola", IsNullable = false)] 
     public List<Hello> worlds;  

     public Component() 
     { 
      worlds = new List<Hello>() {new Hello(), new Hello()}; 
     } 
    } 

    class Cov2xml 
    { 
     static void Main(string[] args) 
     { 
      string xmlFileName = "ip-xact.xml"; 
      Component comp = new Component(); 

      TextWriter writeFileStream = new StreamWriter(xmlFileName); 

      var ser = new XmlSerializer(typeof(Component)); 
      ser.Serialize(writeFileStream, comp); 
      writeFileStream.Close(); 

     } 
    } 
} 

使用此XmlSerializer代碼,我得到此XML文件。在XmlSerializer中使用/不使用XmlElement的不同行爲

enter image description here

我只有一個「世界」的元素,它有兩個你好元素。

但是,當我在worlds varibale之前添加XmlElement時。

[XmlElement("worlds_wola", IsNullable = false)] 
public List<Hello> worlds 

我有兩個worlds_wola元素而不是一個。

enter image description here

這是爲什麼?我如何使用XmlElement來指定標籤的名稱,但只有一個「worlds_wola」元素如下所示?

<worlds_wola> 
    <Hello> 
    ... 
    </Hello> 
    <Hello> 
    ... 
    </Hello> 
</worlds_wola> 
+0

WAG:嘗試使用XmlArrayAttribute代替。 – Will 2012-01-03 22:40:50

回答

0

我發現這正是我想要的基於查爾斯的答案。

[XmlArray("fileSet")] 
[XmlArrayItem(ElementName = "file", IsNullable = false)] 
public List<Hello> worlds; 

在此設置下,我能得到

<fileSet> 
    <file>...</file> 

而不是

<worlds> 
    <Hello>...</Hello> 
相關問題