NemoBlack NemoBlack - 1 month ago 11
C# Question

Capture attributes in XML in C#

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

<ProductoModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>


My Code :

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(content);

XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "http://schemas.datacontract.org/2004/07/WebApi.Models");

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

MessageBox.Show(node.Attributes.GetNamedItem("descripcion").Value);


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?

Answer

<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);

MessageBox.Show(node.InnerText);

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

Comments