zoukankan      html  css  js  c++  java
  • (C#) 操作XML之查找

    有如下XML,如何根据书名(title)Harry Potter显示这个书名的详细内容(detail)呢?

    <?xml version="1.0" encoding="utf-8" ?>
    <bookstore>
      <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <detail>
          <author>Giada De Laurentiis</author>
          <year>2005</year>
          <price>30.00</price>
         </detail>
      </book>
      <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <detail>
          <author>J K.Rowling</author>
          <year>2005</year>
          <price>29.99</price>
        </detail>
      </book>
      <book category="WEB">
        <title lang="en">Learning XML</title>
        <detail>
          <author>Erik T.Ray</author>
          <year>2003</year>
          <price>39.95</price>
        </detail>
      </book>
    </bookstore>

    <detail>结点是<title>兄弟结点,C#提供了NextSibling属性来获取相关数据。

    另外利用XPath的相关语法可以快速的定位到需求的结点。

    (XPath语法参考:http://www.w3school.com.cn/xpath/xpath_syntax.asp,http://www.cnblogs.com/yukaizhao/archive/2011/07/25/xpath.html)

    所以,解题思路为:根据书名Harry Potter 定位到<title lang="en">Harry Potter</title>结点,然后遍历它的下一个兄弟结点的所有的Text结点。

    其中XPath的定位语句为:bookstore/book/title[text()='Harry Potter']

            public string[] GetNextSiblingAllTextNodeInnerText(string node, string textNodeInnerText)
            {
                XmlDocument doc = XMLLoad();
                StringBuilder sbNode = new StringBuilder();
                sbNode.Append(node).Append("[text()='").Append(textNodeInnerText).Append("']");
                XmlNode nd = doc.SelectSingleNode(sbNode.ToString());
                this._TextNodeInnerTexts.Clear(); 
                TraverseTextNodeInnerText(nd.NextSibling);
                return this._TextNodeInnerTexts.ToArray(); 
            }

    修改XPath的定位语句,也可以直接定位到符合条件的detail结点上。如: bookstore/book/title[text()='Harry Potter']/../detail

    输出为:

    J K.Rowling
    2005
    29.99
  • 相关阅读:
    JS中的call()和apply()方法和bind()
    reactjs入门到实战(十)----one-first_app
    49-Reverse Linked List II
    48-Merge Sorted Array
    47-Generate Parentheses
    46.Valid Parentheses
    45-Letter Combinations of a Phone Number
    44-Count and Say
    43-Reverse Nodes in k-Group
    42-Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/fdyang/p/2911249.html
Copyright © 2011-2022 走看看