我正在尝试将 XML 文件反序列化为我的 android 应用程序中的对象,使用 Xamarin Monodroid 开发)。
我用纯 C# 生成我的 XML,将 XML 文件复制到应用程序的 assets 文件夹中,然后在应用程序启动时反序列化它。
[Serializable]
public class MyGreatObject
{
public string ObjectName;
public string ObjectLink;
public string ObjectStuff;
public List<OtherGreatObject> OtherObjects;
public MyGreatObject()
{
OtherObjects = new List<OtherGreatObject>();
}
}
具有共同的OtherGreaterObject
属性(我的意思是字符串格式)。所以,我生成 XML 并有这样的东西:
<?xml version="1.0" encoding="utf-8"?>
<MyGreatObject xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ObjectName>This is the object name</ObjectName>
<ObjectLink>http://www.xamarin-is-awesome.com</ObjectLink>
<ObjectStuff>Description</ObjectStuff>
<OtherObjects>
<OtherGreatObject>...</OtherGreatObject>
<OtherGreatObject>...</OtherGreatObject>
</OtherObjects>
</MyGreatObject>
我尝试像这样反序列化它:
internal static class SerializableXml
{
public static MyGreatObject LoadData(Context context_, string fileName_)
{
MyGreatObject greatObject = new MyGreatObject();
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyGreatObject));
using (Stream input = context_.Assets.Open(fileName_, Android.Content.Res.Access.Buffer))
greatObject = xmlSerializer.Deserialize(input) as MyGreatObject;
}
catch (Exception exception)
{
Android.Util.Log.Error("XML", "ERROR IN LOADING");
Android.Util.Log.Error("XML", exception.ToString());
throw;
}
return greatObject;
}
}
但我得到了错误System.Xml.XmlException: Document element did not appear. Line 1, position 1.
。
at Mono.Xml2.XmlTextReader.Read() [0x00000] in <filename unknown>:0
at System.Xml.XmlTextReader.Read() [0x00000] in <filename unknown>:0
at System.Xml.XmlReader.MoveToCOntent() [0x00000] in <filename unknown>:0
at System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadRoot() [0x00000] in <filename unknown>:0
at System.Xml.Serialization.XmlSerializer.Deserialize(System.Xml.SerializationReader reader) [0x00000] in <filename unknown>:0
我在谷歌上浪费了很多时间,所以我问你。
非常感谢您提供的帮助。