I have XML something like this:
<?xml version="1.0"?>
<a xmlns="http://mynamespace">
<b>
<c val="test" />
<b>
</a>
And I am trying to find the value of the 'val' attribute on the 'c' tag with something like this:
XmlDocument doc = new XmlDocument();
doc.Load("myxml.xml");
nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace(@"mns", "http://mynamespace");
XPathNavigator root = doc.CreateNavigator();
foreach (XPathNavigator nav in root.Select("//mns:c", nsMgr))
{
string val = nav.GetAttribute("val", NS);
Console.WriteLine("val == "+val);
}
My problem is that GetAttribute always returns as an empty string. What am I missing?
Update:
It seems I can fix this by passing an empty string into GetAttribute, i.e.
string val = nav.GetAttribute("val", "");
My question is therefore now: why does this work? Why does 'val' not belong to my namespace despite the XML having been validated against a schema which requires the 'val' attribute (I accidentally omitted this step in my above sample code, but I am validating the XML).