简体   繁体   English

使用列表框读取XML文档

[英]read XML document using listbox

i have a xml document named sms.xml where data is stored like this: 我有一个名为sms.xml的xml文档,其中的数据存储如下:

<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. 这是一个短信,我有1000多个短信,所以我想按名称或地址(无所谓)将它们加载到列表框中,当我单击其中之一时,我想显示所选短信的正文。 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. 在txtName.text行上。 can you help? 你能帮我吗?

ps sorry for my English. ps对不起,我的英语。

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 // . 注意前导//

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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