首页 > 解决方案 > 无法在 Xamarin 中使用 XML 文件填充对象

问题描述

我正在尝试在 Xamarin (Visual Studio) Forms 应用程序中解析一个简单的 XML 文件。我正在使用此处提供的示例

这没用。序列化程序返回一个 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>

标签: xamarin.formsxml-parsing

解决方案


模型中的属性名称需要与 XML 中的节点名称匹配,以便反序列化自动工作。

或者,您可以应用映射属性

[XmlElement("NodeId")]
public int id { get; set; }  

推荐阅读