Return the value for the specific attribute using XPathNodeIterator
November 1, 2009 by Nauman · Leave a Comment
I will use the following XML document in the example below.
<? xml version="1.0" encoding="utf-8" ?>
< users >
< user FirstName ="Tom" LastName ="Adams" Age ="23" />
< user FirstName ="Jhon" LastName ="Brams" Age ="17" />
< user FirstName ="Bill" LastName ="Smith" Age ="33" />
</ users >
The code prints out all the user nodes of the users node that have an age with a value greater than 17
// Read the xml from resource file
string xml = Resources.Users;
using (StringReader sr = new StringReader(xml))
{
XPathDocument document = new XPathDocument(sr);
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);//Selects all the user nodes of the users node that
// have an age with a value greater than 17XPathNodeIterator it = navigator.Select("/users/user[@Age>17]");
while (it.MoveNext())
{
// access the atributes
string firstName = it.Current.GetAttribute("FirstName", ns.DefaultNamespace);
string lastName = it.Current.GetAttribute("LastName", ns.DefaultNamespace);
// Print out
Console.WriteLine( "{0} {1}", firstName, lastName );
}
}