XML以其他格式序列化

时间:2013-02-28 09:37:07

标签: c# .net xml xml-serialization

我有一个类Folders,我需要以指定的格式序列化这个类:

<?xml version="1.0" encoding="UTF-8"?>
<ListFolders  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Folders>
<Id>Dir_1 </Id>
    <Folders>
        <Id>Dir_1_1 </Id>
    </Folders>
    <Folders>
        <Id>Dir_1_2 </Id>
        <Folders>
        <Id>Dir_1_2_1 </Id>
        </Folders>
        <Folders>
        <Id>Dir_1_2_2 </Id>
        </Folders>
    </Folders>
</Folders>
</ListFolders>

但序列化之后我得到了这个:

<?xml version="1.0" encoding="UTF-8"?>
    <ArrayOfFolders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Folders>
    <Id>Dir_1 </Id>
    <ListFolder>
        <Folders>
            <Id>Dir_1_1 </Id>
        </Folders>
        <Folders>
            <Id>Dir_1_2 </Id>
            <ListFolder>
                <Folders>
                    <Id>Dir_1_2_1 </Id>
                </Folders>
                <Folders>
                    <Id>Dir_1_2_2 </Id>
                </Folders>
            </ListFolder>
        </Folders>
    </ListFolder>
    </Folders>
    </ArrayOfFolders>

班级Folder

public class Folders
{
    public string Id { get; set; }
    public List<Folders> ListFolder { get; set; }
}

如何以正确的格式序列化?

UPD:

using (TextWriter reader = new StreamWriter("data.xml"))
{
    (new XmlSerializer(typeof(List<Folders>))).Serialize(reader, data);
}

1 个答案:

答案 0 :(得分:1)

XmlElement属性添加到文件夹列表:

public class Folders
{
    public string Id { get; set; }
    [XmlElement("Folders")]
    public List<Folders> ListFolder { get; set; }
}

序列化Folders对象的结果将是

<?xml version="1.0"?>
<Folders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>Dir_1</Id>
  <Folders>
    <Id>Dir_1_1</Id>
  </Folders>
  <Folders>
    <Id>Dir_1_2</Id>
    <Folders>
      <Id>Dir_1_2_1</Id>
    </Folders>
    <Folders>
      <Id>Dir_1_2_2</Id>
    </Folders>
  </Folders>
</Folders>

BTW Folders是一个非常混乱的类名。 Folder似乎更适合我。