4

Quiero obtener los valores de estos nodos de un archivo XML y cada uno de estos valores asignarle una variable.

Obtengo el archivo de esta forma:

CODE:

var miXML = File.ReadAllText("D:\\20101284981-01-0002-0000000060.xml");

XML:

    <?xml version="1.0" encoding="ISO-8859-1" standalone="no" ?>
    <ar:ApplicationResponse xmlns="urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2"
    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
    xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">

    <cbc:UBLVersionID>2.0</cbc:UBLVersionID>
    <cbc:CustomizationID>1.0</cbc:CustomizationID>
    <cbc:ID>201200000230061</cbc:ID>
    <cbc:IssueDate>2012-06-12</cbc:IssueDate>
    <cbc:IssueTime>10:09:27</cbc:IssueTime>
    <cbc:ResponseDate>2012-06-12</cbc:ResponseDate>
    <cbc:ResponseTime>10:09:30</cbc:ResponseTime>
    <cbc:Note>4031 - Debe indicar el nombre comercial</cbc:Note>
    <cbc:Note>4001 - El numero de RUC del receptor no existe.</cbc:Note>

    <ar:ApplicationResponse>

Probé con XDocument y luego declarar los XNamespace pero cuando hago un xdoc.load("C:// .... "); se cae y me manda un error [ 'ar' es un prefijo no declarado. línea 2, posición 2.]

6
  • y que es lo que probaste hasta ahora?
    – gbianchi
    el 28 dic. 2016 a las 17:51
  • Probé con XDocument y luego declarar los XNamespace pero cuando hago un xdoc.load("C:// .... "); se cae y me manda un error [ 'ar' es un prefijo no declarado. línea 2, posición 2.] el 28 dic. 2016 a las 17:57
  • podrias agregar toda esa info a la pregunta por favor. y no esta mal declarado el prefijo? falta declarar ar en el XML
    – gbianchi
    el 28 dic. 2016 a las 18:48
  • Asi es, falta declarar pero de todas formas es un documento XML que no debo editar, lo importante aqui es obtener los valores de los nodos como por ejemplo: "2.0" del nodo <cbc:UBLVersionID> el 28 dic. 2016 a las 19:30
  • el error que da es pq no puede parsearlo pq esta mal declarado.. entonces que quieres hacer?
    – gbianchi
    el 28 dic. 2016 a las 19:37

1 respuesta 1

1

Tu XML tiene dos errores:

  1. No esta declarado el nameSpace AR
  2. No se esta cerrando el tag ar:ApplicationResponse

Te muestro como lo arregle:

static void Main(string[] args)
    {
        /*
        //XML corregido, agregar namespace ar, cerrar tag ar
        string xml = @"<?xml version='1.0' encoding='ISO-8859-1' standalone='no' ?>
                    <ar:ApplicationResponse xmlns='urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2'
                    xmlns:ar='http://www.w3.org/2000/09/xmldsig#'
                    xmlns:cac='urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2'
                    xmlns:cbc='urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'
                    xmlns:ds='http://www.w3.org/2000/09/xmldsig#'
                    xmlns:ext='urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2'>
                    <cbc:UBLVersionID>2.0</cbc:UBLVersionID>
                    <cbc:CustomizationID>1.0</cbc:CustomizationID>
                    <cbc:ID>201200000230061</cbc:ID>
                    <cbc:IssueDate>2012-06-12</cbc:IssueDate>
                    <cbc:IssueTime>10:09:27</cbc:IssueTime>
                    <cbc:ResponseDate>2012-06-12</cbc:ResponseDate>
                    <cbc:ResponseTime>10:09:30</cbc:ResponseTime>
                    <cbc:Note>4031 - Debe indicar el nombre comercial</cbc:Note>
                    <cbc:Note>4001 - El numero de RUC del receptor no existe.</cbc:Note>
                    </ar:ApplicationResponse>";
                    */

        //Para arreglar tu XML

        string xmlMAL = @"<?xml version='1.0' encoding='ISO-8859-1' standalone='no' ?>
                    <ar:ApplicationResponse xmlns='urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2'
                    xmlns:cac='urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2'
                    xmlns:cbc='urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'
                    xmlns:ds='http://www.w3.org/2000/09/xmldsig#'
                    xmlns:ext='urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2'>
                    <cbc:UBLVersionID>2.0</cbc:UBLVersionID>
                    <cbc:CustomizationID>1.0</cbc:CustomizationID>
                    <cbc:ID>201200000230061</cbc:ID>
                    <cbc:IssueDate>2012-06-12</cbc:IssueDate>
                    <cbc:IssueTime>10:09:27</cbc:IssueTime>
                    <cbc:ResponseDate>2012-06-12</cbc:ResponseDate>
                    <cbc:ResponseTime>10:09:30</cbc:ResponseTime>
                    <cbc:Note>4031 - Debe indicar el nombre comercial</cbc:Note>
                    <cbc:Note>4001 - El numero de RUC del receptor no existe.</cbc:Note>
                    <ar:ApplicationResponse>";

        string xml = xmlMAL;
        //Agrego el namespace AR
        xml = xml.Replace("<ar:ApplicationResponse ", "<ar:ApplicationResponse xmlns:ar='http://www.w3.org/2000/09/xmldsig#' ");
        //Cierro el tag del <ar:ApplicationResponse>
        xml = xml.Replace("<ar:ApplicationResponse>", "</ar:ApplicationResponse>");

        var xmlInput = XDocument.Parse(xml);
        var documento = LeerXML.Procesar(xmlInput);

        Console.WriteLine("UBLVersionID: " +documento.UBLVersionID.ToString());
        Console.WriteLine("CustomizationID: " + documento.CustomizationID.ToString());
        Console.WriteLine("ID: " + documento.ID.ToString());
        Console.WriteLine("IssueDate: " + documento.IssueDate.ToShortDateString());
        Console.WriteLine("IssueTime: " + documento.IssueTime.ToShortTimeString());
        Console.WriteLine("ResponseDate: " + documento.ResponseDate.ToShortDateString());
        Console.WriteLine("ResponseTime: " + documento.ResponseTime.ToShortTimeString());
        int i = 0;
        foreach (var n in documento.Notes) {
            i++;
            Console.WriteLine("Nota" + i.ToString() + ": " + n);
        }

        Console.ReadLine();
    }

Cree la clase LeerXML:

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

namespace LeerXMLConNamespace

{
    public class LeerXML
{

    public static Documento Procesar(XDocument xml)
    {
        try
        {

            XNamespace cbc = @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";

            var doc = new Documento();


            //UBLVersionID
            var UBLVersionID = (from x in xml.Descendants(cbc + "UBLVersionID")
                                select x).FirstOrDefault();
            if (UBLVersionID != null)
            {
                doc.UBLVersionID = decimal.Parse(UBLVersionID.Value == null ? "0.0" : UBLVersionID.Value.ToString());
            }
            //CustomizationID
            var CustomizationID = (from x in xml.Descendants(cbc + "CustomizationID")
                                select x).FirstOrDefault();
            if (CustomizationID != null)
            {
                doc.CustomizationID = decimal.Parse(CustomizationID.Value == null ? "0.0" : CustomizationID.Value.ToString());
            }
            //CustomizationID
            var ID = (from x in xml.Descendants(cbc + "ID")
                                   select x).FirstOrDefault();
            if (ID != null)
            {
                doc.ID = Int64.Parse(ID.Value == null ? "0" : ID.Value.ToString());
            }
            //IssueDate
            var IssueDate = (from x in xml.Descendants(cbc + "IssueDate")
                      select x).FirstOrDefault();
            if (IssueDate != null)
            {
                doc.IssueDate = DateTime.Parse(IssueDate.Value == null ? "1900-01-01" : IssueDate.Value.ToString());
            }
            //IssueTime
            var IssueTime = (from x in xml.Descendants(cbc + "IssueTime")
                             select x).FirstOrDefault();
            if (IssueTime != null)
            {
                doc.IssueTime = DateTime.Parse(IssueTime.Value == null ? "1900-01-01" : "1900-01-01 " + IssueTime.Value.ToString());
            }
            //IssueDate
            var ResponseDate = (from x in xml.Descendants(cbc + "ResponseDate")
                             select x).FirstOrDefault();
            if (ResponseDate != null)
            {
                doc.ResponseDate = DateTime.Parse(ResponseDate.Value == null ? "1900-01-01" : ResponseDate.Value.ToString());
            }
            //IssueTime
            var ResponseTime = (from x in xml.Descendants(cbc + "ResponseTime")
                             select x).FirstOrDefault();
            if (ResponseTime != null)
            {
                doc.ResponseTime = DateTime.Parse(ResponseTime.Value == null ? "1900-01-01" : "1900-01-01 " + ResponseTime.Value.ToString());
            }
            //IssueTime
            var Notes = (from x in xml.Descendants(cbc + "Note")
                                select x).ToList();
            doc.Notes = new List<string>();
            foreach (var n in Notes)
            {
                doc.Notes.Add(n.Value ?? "");
            }             


            return doc;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}
}

Cree la entidad Documento, que contiene los datos del XML:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeerXMLConNamespace
{
    public class Documento
    {
        public decimal UBLVersionID { get; set; }
        public decimal CustomizationID { get; set; }
        public Int64 ID { get; set; }
        public DateTime IssueDate { get; set; }
        public DateTime IssueTime { get; set; }
        public DateTime ResponseDate { get; set; }
        public DateTime ResponseTime { get; set; }
        public List<string> Notes { get; set; }
    }
}

introducir la descripción de la imagen aquí

Por ultimo te anexo la aplicación de ejemplo que hice: Ejemplo leer XML

1
  • 1
    Muchas gracias Cristina, es lo que necesitada (parsear el xml y adaptarlo). Funciona bien ♥ el 28 dic. 2016 a las 21:04

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.