Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So, What i would like is the Code to automatically go through every "Book" looking for the child nodes of "Author" and incrementing them to the BookListView. This will be a foreach loop most likely i think, can you guys help me as im nearly here with this please.

i think something like

foreach (authorvariable)
{
BookListView.Items.Add(LVI);
}


C#
XmlDocument xdoc = new XmlDocument();
xdoc.Load(XMLPath);

XmlNode AuthorNode = xdoc.SelectSingleNode("Books/Book/Author");
string AuthorVariable = AuthorNode.InnerText;

ListViewItem LVI = new ListViewItem(AuthorVariable);

BookListView.Items.Add(LVI);
Posted
Updated 10-Dec-13 11:16am
v2

1 solution

You need to get a collection of "book" nodes first, then you can use your "foreach" loop.

XmlDocument doc = new XmlDocument();
doc.Load("inventory.xml");
//get all books
XmlNodeList books = doc.SelectNodes("//book");
foreach (XmlNode book in books)
{
    // get all authors for each book
    XmlNodeList authors = book.SelectNodes("//author");
    foreach (XmlNode author in authors)
    {
        BookListView.Items.Add(new ListViewItem(author.InnerText));
    }
}
Note: I based this code on this MS XML example file[^]. I think that the xpath code I used is generic enough to also work on your xml file, but you may need to modify the "SelectNodes" statements.

A good quick reference is: XPath Examples[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900