2013-11-05 49 views
0

不能更具体地说出标题的道歉,但我只能通过举例来解释。XML序列化结构

我试图建立一个序列化下面的XML类

<Customize> 
    <Content></Content> 
    <Content></Content> 
    <!-- i.e. a list of Content --> 

    <Command></Command> 
    <Command></Command> 
    <Command></Command> 
    <!-- i.e. a list of Command --> 
</Customize> 

我的C#是:

[XmlRoot] 
public Customize Customize { get; set; } 

public class Customize 
{ 
    public List<Content> Content { get; set; } 
    public List<Command> Command { get; set; } 
} 

然而,这产生(如它应该),如下:

<Customize> 
    <Content> 
     <Content></Content> 
     <Content></Content> 
    </Content> 
    <Command> 
     <Command></Command> 
     <Command></Command> 
     <Command></Command> 
    </Command> 
</Customize> 

是否有一些xml序列化属性可以帮助实现我所需的xml,还是我必须找到另一种写入类的方法?

+0

您可以添加序列化代码? – Styxxy

回答

2

使用XmlElementAttribute来标记您的收藏属性。

public class Customize 
{ 
    [XmlElement("Content")] 
    public List<Content> Content { get; set; } 

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

快速测试代码:

var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } }; 

string result; 

using (var writer = new StringWriter()) 
{ 
    var serializer = new XmlSerializer(typeof(Customize)); 
    serializer.Serialize(writer, item); 
    result = writer.ToString(); 
} 

打印:

<?xml version="1.0" encoding="utf-16"?> 
<Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Content /> 
    <Content /> 
    <Command /> 
    <Command /> 
    <Command /> 
</Customize> 
1
public class Customize 
{ 
    [XmlElement("Content")] 
    public List<Content> Content { get; set; } 

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