C#(2):Xpath导航器XpathNavigator 、System.Xml.XPath

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

一、创建:

  • 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();

    二、读取

    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()方法计算表达式的值;

    //统计图书总价   
    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");

    五、通过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();
    上一篇:软件系统设计方案---GPU光线跟踪系统


    下一篇:XML