• 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();
  • 相关阅读:
    Struts2完全解耦和
    storm 错误汇总
    sublime3 在ubuntu下不能输入中文
    sublime3 10款必备插件
    sublime3 SublimeREPL python3
    sublime3 Package Control不能使用
    Buffer ByteBuffer 缓冲区
    redis cluster批量插入
    延期执行的方案计策略汇总
    linux 免密登录
  • 原文地址:https://www.cnblogs.com/springsnow/p/12883391.html
Copyright © 2020-2023  润新知