简体   繁体   中英

Access to specific element attribute in XML with serialization C#

I have and XML with this structure but I'm trying to access the first "Impuestos" to reach "Traslado" inside it, but it is not working the way I'm doing it, I'm new to working with XML, I don't know how to specify what attribute I need to get.

I'm always getting the values of the structure without "Concepto" and I don't want those values.

<cfdi:Concepto ClaveProdServ="44122016" NoIdentificacion="006001" Cantidad="8.000" ClaveUnidad="XBX" Unidad="Caja" Descripcion="BROCHE ARCHIVO BACO B-182 8CMS CAJAC/50 CAJA AZUL" ValorUnitario="33.55" Importe="268.40" Descuento="0.00">
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado Base="268.40" Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="42.94"/>
        </cfdi:Traslados>
    </cfdi:Impuestos>
</cfdi:Concepto>
<cfdi:Impuestos TotalImpuestosTrasladados="415.76">
    <cfdi:Traslados>
        <cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="415.76"/>
    </cfdi:Traslados>
</cfdi:Impuestos>

This is the code I'm using to do this, this code is based on I've seen in Microsoft forums etc.

public class Comprobante {
    [XmlArrayItem("Concepto")]
    public TConcepto[] Conceptos;

    [XmlElement()]
    public TImpuestos Impuestos;
}

public class TImpuestos
{
    [XmlArrayItem("Traslado")]
    public TTraslado[] Traslados;
}

public class TTraslado
{
    [XmlAttribute()]
    public string Impuesto;
    [XmlAttribute()]
    public string Importe;
}

With this code the values I'm getting are Impuesto = "002" and Importe = "415.76".
But I want to get Impuesto = "002" and Importe = "42.94", I need your help to guide me about the best way to achieve my goal, thanks.

Using Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication120
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement Impuestos = doc.Descendants().Where(x => x.Name.LocalName == "Impuestos").FirstOrDefault();

            XElement Traslado = Impuestos.Descendants().Where(x => x.Name.LocalName == "Traslado").FirstOrDefault();

            string Impuesto =  (string)Traslado.Attribute("Impuesto");
            decimal Importe = (decimal)Traslado.Attribute("Importe");
        }
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM