Tom
Tom

Reputation: 577

Load xml file into multidimensional array

I am pulling my hair out trying to read an XML file into a two dimensional array. I really do not know why the error is appearing. As a matter of fact I have not even done the array part yet. The XML file looks like this:

<?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>

All of the element values come from an array, messageArray[2]. It is possible that I am not creating this right as I am quite new to XML.

Now I am getting the file name from a file dialog control. Here is the code I am using:

    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.
    }
}

So the error I get is "Object reference not set to an instance of an object." Thing is I copied this code from numerous examples that I have seen and some slightly different, but I always get this error. I tried using streamReader and streamWriter but there are carriage returns in the MESSGAE.VALUE so I cannot get that to work. Any help would be much appreciated. Thanks, Tom

Upvotes: 0

Views: 1649

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

As I hinted in the comment, LABEL and MSG are elements, not attributes.

First up, I would re-define message as below - in idiomatic C#, classes and properties are PascalCased:

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

Then this XLinq should work:

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

                    }).ToList();

Upvotes: 1

Related Questions