我試圖反序列化一個xml字符串,但出於某種原因,我得到了標題中指出的錯誤。XmlException:文檔元素沒有出現 - 第1行,位置1
這是我從反序列化的代碼:
public void recieveObject<T>(ref T t){
XmlSerializer xs = new XmlSerializer(typeof(T));
Debug.Log("Waiting for client");
byte[] recievedData = udpc.Receive(ref recieveFromEndPoint);
if(recievedData.Length > 0){
string xmlStr = System.Text.Encoding.UTF8.GetString(recievedData, 0, recievedData.Length);
//xmlStr = xmlStr.Replace("\r","").Replace("\n", "").Replace("\t","").Replace(" ", "");
Debug.Log(xmlStr);
MemoryStream rms = new MemoryStream(1024);
rms.Write (System.Text.Encoding.UTF8.GetBytes(xmlStr), 0, System.Text.Encoding.UTF8.GetBytes(xmlStr).Length);
Debug.Log ("ms: " + System.Text.Encoding.UTF8.GetString(rms.ToArray()));
t = (T) xs.Deserialize(rms);
}
}
你可以從註釋行我甚至嘗試剝離出白色空間看,但沒有eather工作。
這是調用在我的代碼recieveObject功能:
recieveObject<Player>(ref player);
,這裏是我的播放器類:
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
[XmlRoot("player")]
public class Player{
[XmlElement("x")]
public int x;
[XmlElement("y")]
public int y;
[XmlElement("name")]
public string name;
private int maxNameLength = 12;
public Player(){}
public Player(int x, int y, string name){
this.x = x;
this.y = y;
if(name.Length > maxNameLength) name = name.Substring(0, maxNameLength);
this.name = name;
}
}
最後我tryng使用反序列化到XML玩家對象:
<player>
<x>50</x>
<y>100</y>
<name>Tester</name>
</player>
有人能告訴我爲什麼我在標題中出現錯誤嗎?
謝謝你的時間。
看來您收到數據通過UDP通道。請注意,接收超過0個字節並不一定意味着數據是完整的。它可能是無效的XML。否則,我同意阿德里亞諾的回答。 –