I need to read an xml element which has attribute xmlns="http://www.w3.org/2000/09/xmldsig#". XPathSelectElement is giving error "Object reference not set to an instance of an object."
Here is the sample code.
var xml = "<root><tagA>Tag A</tagA><tagB>Tag B</tagB></root>";
XDocument xd = XDocument.Parse(xml);
var str = xd.XPathSelectElement("/root/tagB").ToString(SaveOptions.DisableFormatting);
Console.WriteLine(str);
The result of the above code is:
<tagB>Tag B</tagB>
If I put attribute,
var xml = "<root><tagA>Tag A</tagA><tagB xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Tag B</tagB></root>";
I got error.
Object reference not set to an instance of an object.
Am I missing something here? Can anyone please help me out. (I know I can get by using other methods. I just want to know what I am missing here)
Thank you very much.
You can register the element's namespace in an XmlNamespaceManager:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("ns", "http://www.w3.org/2000/09/xmldsig#");
var str = xd.XPathSelectElement("/root/ns:tagB", nsmgr)
.ToString(SaveOptions.DisableFormatting);
Console.WriteLine(str);
You should read some about XML. The tagB in the second example is in a different namespace. By default, you're querying the empty namespace, if you want to query a different one you need to use a namespace manager and assign the namespace to a prefix, then prefix the element name with this same prefix and it will work again.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xd.CreateNavigator().NameTable);
nsmgr.AddNamespace("xmldsig", "http://www.w3.org/2000/09/xmldsig#");
var str = xd.XPathSelectElement("/root/xmldsig:tagB", nsmgr).ToString(SaveOptions.DisableFormatting);
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