Getting value of an attribute within namespace

2019-06-05 09:05发布

问题:

I am trying to process the following XML:

<rif:Rif xmlns:rif="rif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" rif:numeroRif="XYZXYZXYZ">
    <rif:Nombre>Nombre</rif:Nombre>
    <rif:AgenteRetencionIVA>SI</rif:AgenteRetencionIVA>
    <rif:ContribuyenteIVA>SI</rif:ContribuyenteIVA>
    <rif:Tasa />
</rif:Rif>

An I am using the next code:

XDocument doc = XDocument.Parse(result);
var q = from item in doc.Descendants()
        let attributeType = item.Attribute("AgenteRetencionIVA").Value
        select item;

I have problems to get the attribute rif:AgenteRetencionIVA. How do I to do it?

回答1:

Looks like tou need to specify custom namespace:

string xml = @"...";

XName nameRif = "rif";
XDocument doc = XDocument.Parse(xml);

var q = from item in doc.Descendants()
        let attributeType = item.Attribute(nameRif + "AgenteRetencionIVA")
        select item.Value;
var a = q.ToArray();