为了在我的Xamarin-Forms项目中使用一些XML文件,我正在尝试重新创建此example code 中给出的步骤,但是我总是收到错误消息:
System.Xml.XmlSerializer.dll中发生了'System.InvalidOperationException'类型的异常,但未在用户代码中处理
其他信息:XML文档中存在错误(2,2)。
顺便说一下,示例代码工作正常。
这是我使用的XML文件(作为嵌入式资源):
<?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item>
<Name>One</Name>
<State>Alpha</State>
</Item>
<Item>
<Name>Two</Name>
<State>Two</State>
</Item>
</Items>
这是我使用的C#代码:
using System;
using Xamarin.Forms;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace XmlTestProject
{
public class XmlContentPage : ContentPage
{
public XmlContentPage()
{
//get access to xml file
var assembly = GetType().GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("XmlTestProject.XmlFile.xml");
List<Item> items;
using (var reader = new System.IO.StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<Item>));
items = (List<Item>)serializer.Deserialize(reader);
}
var listView = new ListView();
listView.ItemsSource = items;
Content = new StackLayout
{
Children = {
listView
}
};
}
}
public class Item
{
public string Name { get; set; }
public string State { get; set; }
public override string ToString()
{
return Name;
}
}
}
我正在使用Visual Studio 2015社区版和Xamarin.Forms 2.2.0.5-pre2
答案 0 :(得分:0)
xml应该有 ArrayOfItem 而不是项:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfItem>
<Item>
<Name>One</Name>
<State>Alpha</State>
</Item>
<Item>
<Name>Two</Name>
<State>Two</State>
</Item>
</ArrayOfItem>
答案 1 :(得分:0)
尝试为列表声明一个包装类,然后像这样反序列化:
var serializer = new XmlSerializer(typeof(ItemList));
ItemList items = (ItemList)serializer.Deserialize(reader);
listView.ItemsSource = items.Items;
[XmlRoot("Items")]
public class ItemList
{
public ItemList() {Items = new List<Item>();}
[XmlElement("Item")]
public List<Item> Items {get;set;}
}
public class Item
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("State")]
public string State { get; set; }
}