简体   繁体   中英

read XML document using listbox

i have a xml document named sms.xml where data is stored like this:

<sms address="+995555777777" time="Mar 12, 2013 5:08:09 PM" date="1363093689732" type="2" body="blah blah blah? :D" read="1" service_center="" name="name surname" />

it's one sms and i have more than 1000 sms, so i want to load them in listbox by name, or address (it doesn't matter) and when i click one of them i want to show the body of selected sms. this is my code:

XmlDocument xmlDoc = new XmlDocument();

    public void loadXML()
    {
        xmlDoc.Load("sms.xml");

        XmlNodeList smss = xmlDoc.SelectNodes("//sms");

        foreach (XmlNode sms in smss)
        {
            listBox1.Items.Add(sms.Attributes["address"].Value);
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        loadXML();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        XmlNode node = xmlDoc.SelectSingleNode(string.Format("sms[@name='{0}']", listBox1.SelectedItem));

        txtName.Text = node.Attributes["body"].Value;

    }

and it returns error: "Object reference not set to an instance of an object." on a txtName.text line. can you help?

ps sorry for my English.

It may be a syntax issue, try the following:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    XmlNode node = xmlDoc.SelectSingleNode(string.Format("//sms[@name='{0}']", listBox1.SelectedItem));
    txtName.Text = node.Attributes["body"].Value;
}

Note the leading // .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM