Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an IXmlNamespaceResolver

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

like image 840
Andy Avatar asked Feb 05 '13 16:02

Andy


2 Answers

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);
like image 135
davidbludlow Avatar answered Oct 14 '22 23:10

davidbludlow


You can use an XmlNamespaceManager that implements that interface

Use the constructor which takes an XmlNameTable, passing into it an instance of System.Xml.NameTable via new NameTable(). You can then call AddNamespace function to add namespaces:

var nsMgr = new XmlNamespaceManager(new NameTable());
nsMgr.AddNamespace("ex", "urn:example.org");
nsMgr.AddNamespace("t", "urn:test.org");
doc.XPathSelectElements("/ex:path/ex:to/t:element", nsMgr);
like image 41
iltzortz Avatar answered Oct 14 '22 22:10

iltzortz