1

我有一个类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; }
}

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

升级版:

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

1 回答 1

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>

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

于 2013-02-28T09:51:16.093 回答