NemoBlack NemoBlack - 7 months ago 52
C# Question

Capture attributes in XML in C#

I'm trying to capture the attribute "description" in this XML:

<ProductoModel xmlns:i="" xmlns="">
<descripcion>descripcion 1</descripcion>
<nombre_producto>producto 1</nombre_producto>

My Code :

XmlDocument xDoc = new XmlDocument();

XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "");

XmlNode node = xDoc.DocumentElement.SelectSingleNode("MYNS:ProductoModel", manager);


The problem is I can not capture the attribute "descripcion" and get the following error:

Object reference not set to an instance of an object.

As I can capture the required attribute?


<descripcion> is not attribute. It is element.

You can get any element (or attribute) with a single xpath query.

XmlNode node = xDoc.DocumentElement.SelectSingleNode("/MYNS:ProductoModel/MYNS:descripcion", manager);


Note the character / at the beginning of the xpath expression.