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
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With