Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XPathSelectElement and xml with attribute xmlns="http://www.w3.org/2000/09/xmldsig#" Help

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.

like image 757
Jacob Avatar asked Dec 21 '25 06:12

Jacob


2 Answers

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);
like image 147
Frédéric Hamidi Avatar answered Dec 22 '25 18:12

Frédéric Hamidi


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);
like image 21
Lucero Avatar answered Dec 22 '25 18:12

Lucero