无法在Xamarin中使用XML文件填充对象

问题描述 投票:0回答:1

我试图在Xamarin(Visual Studio)Forms应用程序中解析一个简单的XML文件。我正在使用示例provided here

这是行不通的。序列化程序返回Node对象列表,但它们是空的。我在下面包含我的代码,但它应该与具有一些名称更改的示例相同。我的XML文件位于Solution根目录中,其Build Action配置为Embedded Resource。

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.forms xml-parsing
1个回答
0
投票

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

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

[XmlElement("NodeId")]
public int id { get; set; }  
© www.soinside.com 2019 - 2024. All rights reserved.