将xml文件加载到多维数组中

时间:2014-06-22 21:24:10

标签: c# xml multidimensional-array linq-to-xml

我正在试图将XML文件读入二维数组。我真的不知道错误出现的原因。事实上,我还没有完成阵列部分。 XML文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>

-<TERMINAL_MESSAGE_FILE>
    -<MESSAGE>
        <LABEL>LABEL1</LABEL>
        <MSG>MESSAGE1</MSG>
    </MESSAGE>
    -<MESSAGE>
       <LABEL>LABEL2</LABEL>
       <MSG>MESSAGE2</MSG>
    </MESSAGE>
</TERMINAL_MESSAGE_FILE>

所有元素值都来自数组messageArray [2]。我可能没有创建这个权利,因为我对XML很陌生。

现在我从文件对话框控件中获取文件名。这是我正在使用的代码:

    class message
     {
       public string _label{ get; set; }
       public string _message{ get; set; }
     }

public partial class messageForm : Form
{
    InitializeComponent();
}

private loadBTN_Click(object sender, EventArgs e)
{
    DialogResult result = openMsgFD.ShowDialog();

    if (result == DialogResult.OK)
    {
        XDocument doc = XDocument.Load(openMsgFD.FileName);

        var settingsList = (from element in doc.Root.Elements("MESSAGE")
                           select new message
                           {
                                _label = element.Attribute("LABEL").Value,
                                _message= element.Attribute("MESSAGE").Value

                            }).ToList();

    // will need to deal with putting this into the array but I haven't got that far yet.
    }
}

所以我得到的错误是“对象引用未设置为对象的实例”。 事情是我从我见过的许多例子中复制了这段代码,但有些略有不同,但我总是得到这个错误。我尝试使用streamReader和streamWriter但是MESSGAE.VALUE中有回车符,所以我无法使用它。 任何帮助将非常感激。谢谢,汤姆

1 个答案:

答案 0 :(得分:1)

正如我在评论中暗示的那样,LABEL和MSG是元素,而不是属性。

首先,我将重新定义消息如下 - 在惯用的C#中,类和属性是PascalCased:

public class Message
{
    public string Label { get; set; }
    public string Msg { get; set; }
}

然后这个XLinq应该可以工作:

var settingsList = (from element in doc.Root.Elements("MESSAGE")
                    select new Message
                    {
                        Label = (string)element.Element("LABEL"),
                        Msg = (string)element.Element("MSG")

                    }).ToList();
相关问题