SoFunction
Updated on 2025-03-01

C# Navigator Xpath and XPathNavigator class

The XPathNavigator class contains all methods for moving and selecting the elements required for XML.

1. Create: CreateNavigator

1. XPathNavigator class, if it is fromXPathDocumentCreated in the , it is read-only and can only browse data;

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

2. XPathNavigator class, if it is fromXmlDocumentCreated in , you can edit the document;

XmlDocument doc = new XmlDocument(); 
("./"); 
XPathNavigator nav2 = ();

2. Read: Select()

  • Use the Select() method to query through the XPath statement to obtain the XPathNodeIterator object;
  • Iterates through the XPathNodeIterator iterator, and the MoveNext() method moves the next node; the Current attribute represents the current node;
//Query all nodes in the bookstore child element whose genre attribute value is novelXPathNodeIterator iter = ("/bookstore/book[@genre='novel']");
while (())
{
    //Iterate over all child nodes    XPathNodeIterator newIter = (, false);
    while (())
    {
        (+ " : " +);
    }
}

3. Calculation: Evaluate

Use the Evaluate() method to calculate the value of the expression;

//Total price of books("Total price = {0}", ("sum(bookstore/book/price)"));

IV. Edit

Insert node: First check whether the CanEdit attribute is true, and then use the InsertAfter() method to insert a new node.

XmlDocument doc = new XmlDocument();
("./");
XPathNavigator nav2 = ();
//Judge whether it is editableif ()
{
    XPathNodeIterator iter = ("bookstore/book/price");
    while (())
    {
        //Insert a new node after the current node        ("5");
    }
}
("./");

5. Convert XmlReader, XmlWriter

Convert to XmlReader via XPathNavigator, XmlWriter reads and writes data

//read:XmlReader reader=();
while(())
{
   (());
}

//Write:XmlWriter writer=("./");
(writer);
();

This is all about this article about the C# navigator Xpath and XPathNavigator classes. I hope it will be helpful to everyone's learning and I hope everyone will support me more.