如何加载XML“row”到列表框C#的索引 [英] How to load XML "row" into index of listbox C#

查看:409
本文介绍了如何加载XML“row”到列表框C#的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将xml的单个行加载到列表框索引中。

I'm trying to load a single "row" of xml to a listbox index.

<?xml version="1.0" encoding="utf-8"?>
<!--User | 4/16/2013 @ 10:05 PM-->
<ContactBook>
<Contact>
<Name>
   <Name>personName</Name>
</Name>
<City>
   <City>testCity</City>
</City>
<State>
   <State>testState</State>
</State>
<Phone>
   <Phone>testPhone</Phone>
</Phone>
</Contact>
</ContactBook>

所以我想让名字,城市,州和电话出现在一条线上列表框,然后下一个联系人出现在下一个列表框行中。

So I would like to make name, city, state, and phone show up on one line in a listbox, then have the next contact appear in the next listbox row.

我还想知道是否有人有一些好网站显示有关如何更新XML文件的教程,而不是覆盖它们。

I would also like to know if anyone has some good sites that show tutorials on how to update XML files, rather than overwrite them.

/ 由于评论中的问题而编辑 /

我真的不知道从哪里开始。我的xml文件是从对话框(类中的几个文本框)中编写的,而this.Tag更新了列表框,并保存到xml文件中。但是,如果保存了第二组联系信息,它将覆盖第一组联系信息,而不是附加它。

I didn't really know where to start. My xml file is written from a dialog (a few textboxes in a class) and the this.Tag updates the listbox, and saves to the xml file. However, if a second set of contact info is saved, it overwrites the first one, rather than appending it.

/ EDIT /

感谢LexeRoy,我已经获得了更多的了解,但是,我仍然挂断了。

Thanks to LexeRoy, I've gained a bit more understanding, however, I'm still hung up.

private void updateXml_Click(object sender, EventArgs e)
{
    var xDoc = XDocument.Load(book);
    var listBoxItems = xDoc.Elements("Contact");
    listBox1.Items.Add(listBoxItems);
}

其中book是表示我的xml文件路径的变量,listBox1很明显。
不幸的是,点击按钮后,第一行获得此值:

where book is a variable representing my path to the xml file and listBox1 is obvious. Unfortunately, on button click, the first row gets this value:

System.Xml.Linq.XContainer+<GetElements>d_11 

现在已经声明了数据源,我得到一个抛出异常:

Now that the datasource has been declared, I get a thrown exception:

推荐答案

您可以使用 XDocument 您可以在其中表示XML文档并迭代其每个项目。对于您的示例,

You can use XDocument where you can represent your XML document and iterate each of its items. For your example,

您可以为联系创建一个对象,您将获得名称城市电话 properties。

You can create an object for a Contact where you will have a Name, City, State, and Phone properties.

var xDoc = XDocument.Load("ContactBook.xml");
var listBoxItems = xDoc.Elements("Contact"); //This will be a list of IEnumerable<XElement> child elements of Contact xml tag

然后您可以通过代码操作这些内容。

Then you can manipulate those things via your code.

编辑:

listBox1.DataSource = listBoxItems.ToList();
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Value";

这篇关于如何加载XML“row”到列表框C#的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆