Using the GetAttribute method of the XPathNavigator to get an attribute value easily
Posted: (EET/GMT+2)
Some XML stuff for a change, not everything is JSON. :-) I'm currently working on .NET and C# project which includes XML manipulation. Some XML values are stored using attributes, and I'm mostly using a XPathNavigator class for the job.
There's a little caveat in this class which I wanted to blog about. When calling the GetAttribute method, you need to specify the attribute name along with the namespace. However, if your XML input data does not contain any (explicit) namespaces, what should you give as the namespace parameter?
The answer is that you need to give it an empty string ("" or String.Empty). If you give the namespace parameter a null value instead, the attribute name will not be found, but there's no error message given. Instead, the GetAttribute method returns an empty string.
Here's a quick example. Assume you have a sample XML data element like this:
<product version=”1.0”>Acme Product 1234</product>
Then, the C# code to retrieve the version attribute value would be:
XPathNavigator navi = ...; string version = navi.Current.GetAttribute(“version”,””);
Good luck!