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.
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.
/EDIT due to question in a comment/
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/
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);
}
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:
This is the way I load XML:
Hope this helps you.
You can use
XDocument
where you can represent your XML document and iterate each of its items. For your example,You can create an object for a
Contact
where you will have aName
,City
,State
, andPhone
properties.Then you can manipulate those things via your code.
EDIT:
If what you want is to display the "members" (and their values I guess) of some "Contact" object in a listbox, one approach could be to create a class for the "Contact" object and another for its "members":
These classes can probably help handling the fields in the dialog, too.
Then as you read the xml you instantiate a new
ObjectMember
which youAdd
to your list of members (or whatever works out to give you that!). Linq to Xml is probably the simplest and most enjoyable way to go.When you have all members, you can bind your
ListBox
to the contact'sMembers
list, but the implementation of that depends on whether you're in the WinForms or in the WPF realm.There is a easier method to bind by using Dictionary object
Reference Link