How do I get an IXmlNamespaceResolver

Andy picture Andy · Feb 5, 2013 · Viewed 7.5k times · Source

I'm trying to call the XElement.XPathSelectElements() overload that requires an IXmlNamespaceResolver object. Can anyone show me how to get (or make) an IXmlNamespaceResolver? I have a list of the namespaces I want to use in my query

Answer

davidbludlow picture davidbludlow · Feb 6, 2016

Use new XmlNamespaceManager(new NameTable()).

For example, if you have an XML document that uses namespaces like

var xDoc = XDocument.Parse(@"<m:Student xmlns:m='http://www.ludlowcloud.com/Math'>
    <m:Grade>98</m:Grade>
    <m:Grade>96</m:Grade>
</m:Student>");

then you can get the Grade nodes by doing

var namespaceResolver = new XmlNamespaceManager(new NameTable());
namespaceResolver.AddNamespace("math", "http://www.ludlowcloud.com/Math");
var grades = xDoc.XPathSelectElements("//math:Student/math:Grade", namespaceResolver);