<bookstore>
<book>
<title>bob</title>
<author>fred</author>
</book>
...
使用 C# XmlTextReader
,我如何打印出作者,只有当书名是bob
?
您可以使用 XmlDocument
希望你明白需要做什么。
您可以使用 xpath 查找节点:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("yourfile.xml");
string path = "/bookstore/book[title='bob']"; // find the book node only when the book title is bob
XmlNode node = xmlDoc.SelectSingleNode(path); // get the book node
string author = node.SelectSingleNode("author").InnerText; // find the author node, return its inner text
如果书名的值不是唯一的,您可以使用 XmlDocument.SelectNodes 代替。
XmlNodeList books = xmlDoc.SelectNodes(path); // find all books whose title is bob
foreadh(XmlNode book in books)
{
string author = node.SelectSingleNode("author").InnerText;
...
}