zoukankan      html  css  js  c++  java
  • C#(2):Xpath导航器XpathNavigator 、System.Xml.XPath

    XPathNavigator类包含移动和选择XML所需元素的所有方法。

    一、创建:CreateNavigator

    • XPathNavigator类,如果是从XPathDocument中创建,则是只读的,只能浏览数据;
    • XPathDocument doc = new XPathDocument("./books.xml");
      XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
    • XPathNavigator类,如果是从XmlDocument中创建,则可以编辑文档;
    • XmlDocument doc = new XmlDocument(); 
      doc.Load("./books.xml"); 
      XPathNavigator nav2 = doc.CreateNavigator();

    二、读取:Select()

    1. 使用Select()方法通过XPath语句查询,得到XPathNodeIterator对象;
    2. 遍历XPathNodeIterator迭代器,MoveNext()方法移动下一个节点;Current属性表示当前节点;
    //查询bookstore的子元素book中genre属性值为novel的所有节点
    XPathNodeIterator iter = nav.Select("/bookstore/book[@genre='novel']");
    while (iter.MoveNext())
    {
        //迭代所有子代节点
        XPathNodeIterator newIter = iter.Current.SelectDescendants(XPathNodeType.Element, false);
        while (newIter.MoveNext())
        {
            Console.WriteLine(newIter.Current.Name + " : " + newIter.Current.Value);
        }
    }

    三、计算:Evaluate

    使用Evaluate()方法计算表达式的值;

    //统计图书总价   
    Console.WriteLine("Total price = {0}", nav.Evaluate("sum(bookstore/book/price)"));

    四、编辑

    插入节点:先检查CanEdit属性是否为true,再使用InsertAfter()方法插入新节点。

    XmlDocument doc = new XmlDocument();
    doc.Load("./books.xml");
    XPathNavigator nav2 = doc.CreateNavigator();
    //判断是否可编辑
    if (nav2.CanEdit)
    {
        XPathNodeIterator iter = nav2.Select("bookstore/book/price");
        while (iter.MoveNext())
        {
            //在当前节点之后插入新节点
            iter.Current.InsertAfter("<disc>5</disc>");
        }
    }
    doc.Save("./newBooks.xml");

    五、转换XmlReader ,XmlWriter

    通过XPathNavigator转换为XmlReader ,XmlWriter读写数据

    //读:
    XmlReader reader=nav.ReadSubtree();
    while(reader.Read())
    {
       Console.Write(reader.ReadOuterXml());
    }
    
    //写:
    XmlWriter writer=XmlWriter.Create("./1.xml");
    nav.WriteSubtree(writer);
    writer.Close();
  • 相关阅读:
    hdu 2647 Reward
    hdu 2094 产生冠军
    hdu 3342 Legal or Not
    hdu 1285 确定比赛名次
    hdu 3006 The Number of set
    hdu 1429 胜利大逃亡(续)
    UVA 146 ID Codes
    UVA 131 The Psychic Poker Player
    洛谷 P2491消防 解题报告
    洛谷 P2587 [ZJOI2008]泡泡堂 解题报告
  • 原文地址:https://www.cnblogs.com/springsnow/p/12883391.html
Copyright © 2011-2022 走看看