2012-01-03 63 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> 
相关问题