World’s smallest XML XPath Tutorial

Posted on May 29, 2008. Filed under: XPath | Tags: , |

XMLXPath is a technique that provides a way to locate and process items in XML documents by using an addressing syntax based on a path through the document’s logical structure or hierarchy.

XPath is a very important topic in XML, it has so many advantages when reading an XML file.

  • You can directly access a XML node based on its Attribute value or child node’s value.
  • Do XML Node sorting based on value of attributes or child nodes.
  • Manipulate XML in a very convenient way.
  • Save time.

So let’s start coding and learning…

You need the following to jump start XPath in C#:

1. XMLNameSpaceManager

Every XML that we come across has a name space. Some times it has multiple or it may have none too. Unless and until it doesn’t have a name space (a rare case) we require a name space manager. Name spaces defines scope with in XML, it describes which nodes fall under which scope.

So let’s go ahead a define our name space manager:

private XmlNamespaceManager xmlNameSpaceManager;
public XmlNamespaceManager MyNamespaceManager
{
  get
  {
    if (null == this.xmlNameSpaceManager)
    {
       XmlNameTable xmlNameTable = new NameTable();
       this.xmlNameSpaceManager = new XmlNamespaceManager(xmlNameTable);
       this.xmlNameSpaceManager.AddNamespace("nsm", "http://www.example.com/ns/xml");
     }
     return this.xmlNameSpaceManager;
  }
}

Check what we have done above:

Take a XmlNamespaceManager object built upon a XmlNameTable object.

Add our namespace (Eg: http://www.example.com/ns/xml in the above case) and assign a prefix (like a nickname for a big name) to it. This prefix will be used for searching the name space in the XML.

2. Ready to Search:

Now once you have defined your name space manager you are ready to search your nodes and attributes and XML fragments. Let’s write the top level code for all subsequent points.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("myxml.xml");
XmlElement root = xmlDocument.DocumentElement;

3. Searching for XMLNode

XmlNode xnRecord = root.SelectSingleNode("nsm:Record", MyNamespaceManager);

This will select the first Node under the root node which matches the name “Record”, if none is found, it will be null

4. Searching XMLNode by Attribute value

XmlNode xnRecord = root.SelectSingleNode("nsm:Record[@Id='AB']", MyNamespaceManager);

This will return a “Record” whose attribute “Id” value matches “AB”. Notice we are using “@” symbol which means search attributes.

5. Searching XMLNode by ChildNode’s inner text

XmlNode xnRecord = root.SelectSingleNode("nsm:Record[Name='Sunil']", MyNamespaceManager);

Notice to search by ChildNode’s value we will omit “@” symbol.

6. Searching XMLNodeList

Similar concepts can be utilized for XMLNodeList as well, but with one change:

XmlNodeList xnlRecords = root.SelectNodes("nsm:Record", MyNamespaceManager);

Use SelectNodes instead of SelectSingleNode and XmlNodeList instead of XmlNode, rest every thing remains same.

7. Sorting

XPathNavigator navigator = xmlDocument.CreateNavigator();
XPathExpression selectExpression = navigator.Compile(navigateNode);
selectExpression.SetContext(MyNamespaceManager);
selectExpression.AddSort("@EmpId", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
XPathNodeIterator nodeIterator = navigator.Select("/nsm:root/nsm:record");
while (nodeIterator.MoveNext())
{
   XmlElement xnm = (XmlElement)((IHasXmlNode)nodeIterator.Current).GetNode();
   //Do other required operations here
}

Thats all and we are done with all basic operation with XPath in C#.
Do let me know if I have missed some thing and you would like me to incorporate it in this tutorial.

Advertisements

Make a Comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

One Response to “World’s smallest XML XPath Tutorial”

RSS Feed for My .NET Blog Comments RSS Feed

[…] – bookmarked by 1 members originally found by jacobysmine on 2008-11-20 World’s smallest XML XPath Tutorial https://mydotnet.wordpress.com/2008/05/29/worlds-smallest-xml-xpath-tutorial/ – bookmarked by 4 […]


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: