如何在xml中查找单个子节点

时间:2013-03-07 03:11:53

标签: c# xml

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

使用C#XmlTextReader,如何在图书标题为bob时打印出作者?

2 个答案:

答案 0 :(得分:0)

您可以使用XmlDocument

  1. 将getElementByTagName用于“book”
  2. 遍历元素并使用条件获取包含“BOB”的正确标题
  3. 从该父书节点获取作者值。
  4. 希望你明白需要做些什么。

答案 1 :(得分: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;
    ...
}