C#导航器Xpath与XPathNavigator类

2022-11-13 09:11:22 xpath 导航 XPathNavigator

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

一、创建:CreateNavigator

1、XPathNavigator类,如果是从XPathDocument中创建,则是只读的,只能浏览数据;

XPathDocument doc = new XPathDocument("./books.xml");
XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();

2、XPathNavigator类,如果是从XmlDocument中创建,则可以编辑文档;

XmlDocument doc = new XmlDocument(); 
doc.Load("./books.xml"); 
XPathNavigator nav2 = doc.CreateNavigator();

二、读取:Select()

  • 使用Select()方法通过XPath语句查询,得到XPathnodeIterator对象;
  • 遍历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("5");
    }
}
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();

到此这篇关于C#导航器Xpath与XPathNavigator类的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

相关文章