1

我正在使用 DataContractSerializer 反序列化具有多个集合的 Xml。xml 如下所示

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<collectionContents>
    <collection>
        <name>Folder1</name>
        <id>33399446</id>
        <contents>TestFolder1</contents>
    </collection>
    <collection>
      <name>Folder2</name>
      <id>566494</id>
      <contents>TestFolder2</contents>
    </collection>
    <file>
        <name>2012-08-24_171456.jpg</name>
        <id>33399624</id>
        <size>47612</size>
        <lastModified>2012-12-18T18:54:50.000-08:00</lastModified>
    </file>
    <file>
        <name>1033.ico</name>
        <id>33412726</id>
        <size>23246</size>
        <lastModified>2012-12-18T20:37:15.000-08:00</lastModified>
    </file>
</collectionContents>

我创建了 DataContractSerializer 来反序列化 xml。

[DataContract(Namespace = "")]
class Item
{
    [DataMember(Name = "name")]
    public string name;
    [DataMember(Name = "id")]
    public string id;
}

[DataContract(Name = "collection", Namespace = "")]
class Folder : Item
{
    [DataMember(Name = "contents")]
    public string contents;
}

[DataContract(Name = "file", Namespace = "")]
class File : Item
{
    [DataMember(Name = "size")]
    public long size;
    [DataMember(Name = "lastModified", Order = 3)]
    public string lastModified;
}

[CollectionDataContract(Name = "collectionContents", Namespace = "")]
class Folders : List<Folder>
{}

[CollectionDataContract(Name = "collectionContents", Namespace = "")]
class Files : List<File>
{}

我可以使用两个 DataContractSerializer 来获取两个集合文件和文件。

DataContractSerializer folderSer = new DataContractSerializer(typeof(Folderes));
DataContractSerializer fileSer = new DataContractSerializer(typeof(Files));

但它需要反序列化两次,有谁知道有没有办法只使用一个 DataContractSerializer 来获得两个集合?

我在下面累了,但它返回的文件夹/文件数为 0。

[DataContract(Name = "collectionContents", Namespace = "")]
class ItemCollectionList
{
    [DataMember(Name = "collection")]
    public Folders folders;     // Return count is 0;
    [DataMember(Name = "file")]
    public Files files;         // Return count is 0;
}
4

1 回答 1

0

你能用and元素将你的and元素包装在你的 XML 中吗?(以便它更好地匹配您的类型)collectionfilefoldersfilesItemCollectionList

于 2012-12-21T11:58:54.903 回答