我正在尝试在Xamarin(Visual Studio)Forms应用程序中解析一个简单的XML文件。我正在使用示例provided here
它不起作用。序列化程序返回Node对象的列表,但它们为空。我在下面包含了我的代码,但应该与示例相同,但要进行一些名称更改。我的XML文件位于“解决方案”根目录中,其“构建操作”已配置为嵌入式资源。
namespace EZCal
{
public partial class MainPage : ContentPage
{
// description of a menu tree node
public class Node
{
// TODO: move strings to external file so they can be Localized
public int id { get; set; } // the ID of this node. Never null
public int idParent { get; set; } // NULL for top-level nodes
public String desc1 { get; set; } // text to be displayed - line 1
public String desc2 { get; set; } // text to be displayed - line 1
public String command { get; set; } // command string to be sent to device
}
public MainPage()
{
InitializeComponent();
this.parseXML();
}
void parseXML() {
var assembly = System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
System.IO.Stream stream = assembly.GetManifestResourceStream("EZCal.MenuDefinitions.xml");
List<Node> menuNodes;
using (var reader = new System.IO.StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<Node>));
menuNodes = (List<Node>) serializer.Deserialize(reader);
}
var listView = new ListView();
listView.ItemsSource = menuNodes;
}
}
}
这是我的XML文件:
<?xml version="1.0" encoding="UTF-8" ?>
<ArrayOfNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Node>
<NodeId>1</NodeId>
<ParentId>0</ParentId>
<Display1>Home line 1</Display1>
<Display2>Home line 2</Display2>
<Command>Home Command</Command>
</Node>
<Node>
<NodeId>2</NodeId>
<ParentId>1</ParentId>
<Display1>Help line 1</Display1>
<Display2>Help line 2</Display2>
<Command>Help Command</Command>
</Node>
<Node>
<NodeId>3</NodeId>
<ParentId>1</ParentId>
<Display1>Diags line 1</Display1>
<Display2>Diags line 2</Display2>
<Command>Diags Command</Command>
</Node>
<Node>
<NodeId>4</NodeId>
<ParentId>1</ParentId>
<Display1>Access line 1</Display1>
<Display2>Access line 2</Display2>
<Command>Access Command</Command>
</Node>
</Node>
</ArrayOfNode>
答案 0 :(得分:0)
模型中的属性名称需要与XML中的节点名称匹配,以便反序列化自动进行。
或者,您可以应用映射属性
[XmlElement("NodeId")]
public int id { get; set; }