我有以下课程:
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
public class Resource
{
[XmlAttribute("name")]
public string m_Name { get; set; }
public string[] ItemDrop;
}
这个XML文件:
<ResourceData>
<Resources>
<Resource name="Iron Ore">
<ItemDrop type="array">
<value>Iron Piece</value>
</ItemDrop>
</Resource>
<Resource name="Tree">
<ItemDrop type="array">
<value>Log</value>
<value>Leaves</value>
<value>Apple</value>
</ItemDrop>
</Resource>
</Resources>
</ResourceData>
我正在尝试反序列化文件并将这两个Resource对象放在数组中。
它正确读取m_Name但ItemDrop数组中没有任何内容。
这是我加载数据的方式:
public static ResourceContainer Load(string path)
{
var serializer = new XmlSerializer(typeof(ResourceContainer));
using (var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as ResourceContainer;
}
}
答案 0 :(得分:0)
您肯定需要XmlArrayItem
属性:
public class Resource
{
[XmlAttribute("name")]
public string m_Name { get; set; }
[XmlArrayItem("value")]
public string[] ItemDrop;
}
答案 1 :(得分:0)
试试xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Resource resourse = new Resource();
resourse.ReadXML(FILENAME);
}
}
public class Resource
{
public static List<Resource> resources { get; set; }
public string m_Name { get; set; }
public string[] ItemDrop;
public void ReadXML(string filename)
{
XDocument doc = XDocument.Load(filename);
resources = doc.Descendants("Resource").Select(x => new Resource() {
m_Name = (string)x.Attribute("name"),
ItemDrop = x.Element("ItemDrop").Elements("value").Select(y => (string)y).ToArray()
}).ToList();
}
}
}