熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#高級編程:使用XPath命名空間中的類[1]

2022-06-13   來源: .NET編程 
    ——此文章摘自《C#高級編程(第版)》定價元 特價元 購買

    要理解這些類的用法最好是查看一下迭代booksxml文檔的代碼確定導航是如何工作的為了使用這些示例首先需要添加對SystemXmlXsl 和 SystemXmlXPath命名空間的引用如下所示
    using SystemXmlXPath;
    using SystemXmlXsl;

    這個示例使用了文件booksxpathxml它類似於前面使用的booksxml但booksxpathxml添加了兩本書下面是窗體代碼這段代碼在XPathXSLSample文件夾中
    private void button_Click(object sender SystemEventArgs e)
    {
       //modify to match your path structure
       XPathDocument doc=new XPathDocument(\\\\\\booksxpathxml);
       //create the XPath navigator
       XPathNavigator nav=docCreateNavigator();
       //create the XPathNodeIterator of book nodes
       // that have genre attribute value of novel
       XPathNodeIterator iter=navSelect(/bookstore/book[@genre=novel]);
     
       while(iterMoveNext())
       {
          LoadBook(iterCurrent);
       }
    }
    private void LoadBook(XPathNavigator lstNav)
    {
       //We are passed an XPathNavigator of a particular book node
       //we will select all of the descendents and
       //load the list box with the names and values
     
       XPathNodeIterator iterBook=lstNavSelectDescendants
                                  (XPathNodeTypeElement false);
       while(iterBookMoveNext())
          listBoxItemsAdd(iterBookCurrentName + :
                                                   + iterBookCurrentValue);
    }

    在button_Click()方法中首先創建XPathDocument(叫做doc)其參數是要打開的文檔的文件和路徑字符串下面一行代碼創建XPathNavigator
    XPathNavigator nav = docCreateNavigator();

    本例用Select方法獲取genre屬性值為novel的所有節點然後使用MoveNext()方法迭代書籍列表中的所有小說

    要把數據加載到列表框中使用XPathNodeIteratorCurrent屬性根據XPathNodeIterator指向的節點創建一個新的XPathNavigator對象在本例中為文檔中的一個book節點創建一個XPathNavigator

    LoadBook()方法提取這個XPathNavigator調用Select方法的另一個重載方法SelectDescendants創建另一個XPathNavigator這樣XPathNodeIterator就包含了給LoadBook方法發送的book節點的所有子節點

    然後在這個XPathNodeIterator上執行另一個MoveNext()循環給列表框加載元素名稱和元素值在執行代碼後顯示所示的屏幕圖注意只列出了小說

[]  []  


From:http://tw.wingwit.com/Article/program/net/201311/14664.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.