0
<bookstore>
    <book>
         <title>bob</title>
         <author>fred</author>
     </book>
...

使用 C# XmlTextReader,我如何打印出作者,只有当书名是bob

4

2 回答 2

0

您可以使用 XmlDocument

  1. 将 getElementByTagName 用于“书”
  2. 遍历元素并使用条件来获得包含“BOB”的正确标题
  3. 从该父书节点获取作者值。

希望你明白需要做什么。

于 2013-03-07T04:00:36.220 回答
0

您可以使用 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;
    ...
}
于 2013-03-11T15:22:39.660 回答