问题描述
所以,我想要的是Code自动遍历每个Book寻找Author的子节点并将它们递增到BookListView。这将是一个foreach循环,我认为很可能,你们可以帮助我,因为我几乎就在这里。
i想想像
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);
}
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);
推荐答案
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));
}
}
注意:我将此代码基于此 []。我认为我使用的xpath代码足够通用,也适用于你的xml文件,但你可能需要修改SelectNodes语句。
快速好参考是: []
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[^]
这篇关于ListView中每个节点类型的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!