2011-08-24 118 views
2

Helio公司,Xml序列 - 集合屬性

此代碼:

[Serializable] 
[XmlRoot("A")] 
public class A 
{ 
    public B B { get; set; } 

    public void Save() 
    { 
     string settingsFilePath = string.Format("test.xml"); 
     XmlSerializer serializer = new XmlSerializer(typeof(A)); 
     TextWriter writer = new StreamWriter(settingsFilePath); 
     XmlSerializerNamespaces ns = new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty) }); 
     serializer.Serialize(writer, this, ns); 
     writer.Close(); 
    } 
} 

public class B 
{ 
    [XmlAttribute("c")] 
    public string C { get; set; } 

    public List<D> D { get; set; } 
} 

public class D 
{ 
    [XmlAttribute("e")] 
    public string E { get; set; } 
} 

A a = new A(); 
a.B = new B(); 
a.B.C = "c"; 
a.B.D = new List<D>(); 
D d = new D(); 
d.E = "e"; 
a.B.D.Add(d); 
a.B.D.Add(d); 
a.B.D.Add(d); 
a.Save(); 

產生這樣的XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<A> 
    <B c="c"> 
    <D> 
     <D e="e" /> 
     <D e="e" /> 
     <D e="e" /> 
    </D> 
    </B> 
</A> 

有什麼辦法來產生這樣的結構XML:?

<?xml version="1.0" encoding="utf-8"?> 
<A> 
    <B c="c"> 
    <D e="e" /> 
    <D e="e" /> 
    <D e="e" /> 
    </B> 
</A> 
+0

OK,XmlElement的做的工作 – anth

回答

4

裝飾在B類

[XmlElement("D")] 
public List<D> D { get; set; }