如何使用C#XmlSerializer对此XML文档结构进行反序列化?如何反序列化这个XML文档?
...
<Data>
<Hotspot>
<Properties>
<xPos>0.5</xPos>
<yPos>0.3</yPos>
<alpha>0.1</alpha>
</Properties>
<Properties>
<xPos>0.4</xPos>
<yPos>0.7</yPos>
<alpha>0.2</alpha>
</Properties>
</Hotspot>
<Hotspot>
<Properties>
<xPos>0.1</xPos>
<yPos>0.2</yPos>
<alpha>0.9</alpha>
</Properties>
<Properties>
<xPos>0.2</xPos>
<yPos>0.3</yPos>
<alpha>0.8</alpha>
</Properties>
</Hotspot>
</Data>
我在Unity工作,我想用这个XML文档中的位置数据驱动一个GUI元素。
这里是我的反序列化代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using System;
using System.IO;
public class Data
{
public List<Hotspot> Hotspot;
[XmlIgnore]
public Data XmlData;
public void Deserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(Data));
TextReader reader = new StreamReader(@"D:\Unity Projects\Axion800_Kabine\Assets\hspositions.xml");
object obj = deserializer.Deserialize(reader);
XmlData = (Data)obj;
reader.Close();
}
}
public class Hotspot
{
public List<Properties> Properties = new List<Properties>();
}
public class Properties
{
public float xPos;
public float yPos;
public float alphaValue;
}
只是为了测试目的我做了另一个脚本实际使用XML数据,并将其连接到一个GUI元素:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class UseXMLData : MonoBehaviour
{
private RectTransform rectTrans;
private int _index = 0;
private Data data;
void Awake()
{
data = new Data();
data.Deserialize();
rectTrans = GetComponent<RectTransform>();
}
void Update()
{
rectTrans.anchoredPosition = new Vector2(data.XmlData.Hotspot[0].Properties[_index].xPos, data.XmlData.Hotspot[0].Properties[_index].yPos);
_index++;
if(_index == data.XmlData.Hotspot[0].Properties.Count - 1)
_index = 0;
}
}
这是我收到的错误消息:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[Properties].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
UseXMLData.Update() (at Assets/UseXMLData.cs:21)
在我看来,XML数据从来没有成功完全读取,以便数组不包含数据。我在设置Data,Hotspot和Properties类的过程中做了什么错误?
非常感谢您的帮助!
肖恩
“我没有在我面前的代码,但它不工作,我认为这是*的东西*这样的“...请发布实际失败的代码,而不是要求他人尝试你可能失败的代码。 – Jonathan
对不起,没有发布实际失败的代码。我现在更新了我的问题。 – SeanThreeD