我有一个XML文件(用于Tiled图块编辑器):( xml的片段)

<map version="1.0" orientation="orthogonal" renderorder="right-down" width="64" height="64" tilewidth="32" tileheight="32" nextobjectid="1">
 <tileset firstgid="1" name="GrassyTile_01" tilewidth="32" tileheight="32" tilecount="4" columns="2">
  <image source="GrassyTile_01.png" width="64" height="64"/>
 </tileset>
 <tileset firstgid="5" name="BlackTile_01" tilewidth="32" tileheight="32" tilecount="1" columns="1">
  <image source="BlackTile_01.jpg" width="32" height="32"/>
 </tileset>


关于“ tileset”元素,可以有X个元素,但它们不包含在XmlArray中,而是一个接一个。

我正在寻找一种使用XMLSerializer将这些元素反序列化为数组的方法,但是我找不到执行此操作的正确方法。

这是我的代码:

 [XmlRoot("map")]
        public class XMLMAP
        {
            [XmlAttribute("version")]
            public string Version;
            [XmlAttribute("orientation")]
            public string Orientation;
            [XmlAttribute("renderorder")]
            public string Renderorder;
            [XmlAttribute("width")]
            public int Width;
            [XmlAttribute("height")]
            public int Height;
            [XmlAttribute("tilewidth")]
            public int Tilewidth;
            [XmlAttribute("tileheight")]
            public int TileHeight;
            [XmlAttribute("nextobjectid")]
            public int NextObjectID;
            [XmlArray]
            public XMLMAP_TILESET[] TileSets;
            [XmlRoot("tileset")]
            public class XMLMAP_TILESET
            {
                [XmlAttribute("firstgid")]
                public string FirstGID;
                //No need for rest of code
            }
        }


任何人都知道这是否可行,还是我不得不求助于XMLReader?

最佳答案

尝试将您的XMLMAP类重新定义为:

[XmlRoot("map")]
public class XMLMAP
{
    [XmlAttribute("version")]
    public string Version;
    [XmlAttribute("orientation")]
    public string Orientation;
    [XmlAttribute("renderorder")]
    public string Renderorder;
    [XmlAttribute("width")]
    public int Width;
    [XmlAttribute("height")]
    public int Height;
    [XmlAttribute("tilewidth")]
    public int Tilewidth;
    [XmlAttribute("tileheight")]
    public int TileHeight;
    [XmlAttribute("nextobjectid")]
    public int NextObjectID;

    [XmlElement("tileset")]
    public List<TileSet> TileSets;
}

[XmlRoot("tileset")]
public class TileSet
{
    [XmlAttribute("firstgid")]
    public string FirstGID;
}


其中XMLMAP包含List<TileSet>,然后TileSet被定义为包含所有必需属性等的单独类。

我现在可以反序列化

var serializer = new XmlSerializer(typeof(XMLMAP));

var reader = new StreamReader(path);
var map = (XMLMAP)serializer.Deserialize(reader);
reader.Close();


并且可以看到map包含2个TileSet的列表

请注意,我只能在提供的xml末尾添加结束</map>标记后才能执行此操作。

希望能有所帮助

09-25 19:37