Crear Archivo XML a partir de Clase (UBL 2.1)

Por pedido de varias personas voy a publicar como se puede generar el archivo XML con la clase C# generada en el post GENERAR CLASE C# DESDE XSD (UBL 2.1), vamos a comenzar:

Creamos una solución, en este caso de consola con la siguiente estructura

Editado

Vemos que tenemos agregado la clase Factura_v2_1.cs, y vamos agregar el siguiete codigo en la clase
public partial class InvoiceType
    {
        [XmlAttribute(AttributeName = "xmlns")]
        public string Xmlns { get; set; }
        [XmlAttribute(AttributeName = "cac", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Cac { get; set; }
        [XmlAttribute(AttributeName = "cbc", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Cbc { get; set; }
        [XmlAttribute(AttributeName = "ccts", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Ccts { get; set; }
        [XmlAttribute(AttributeName = "ds", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Ds { get; set; }
        [XmlAttribute(AttributeName = "ext", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Ext { get; set; }
        [XmlAttribute(AttributeName = "qdt", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Qdt { get; set; }
        [XmlAttribute(AttributeName = "udt", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Udt { get; set; }
        [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }

        ...

Luego en la clase Program.cs vamos a instanciarla y llenar datos de prueba, escribimos el siguiente código:

static void Main(string[] args)
        {
            string numeroFactura = "F001-0000322";
            InvoiceType facturaXML = new InvoiceType();
            //------Namespace necesarios para el UBL
            facturaXML.Cac = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
            facturaXML.Cbc = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
            facturaXML.Ccts = "urn:un:unece:uncefact:documentation:2";
            facturaXML.Ds = "http://www.w3.org/2000/09/xmldsig#";
            facturaXML.Ext = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2";
            facturaXML.Qdt = "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2";
            facturaXML.Udt = "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2";
            //------
            //-----Datos de pruebas de facturas
            facturaXML.UBLVersionID = new UBLVersionIDType();
            facturaXML.UBLVersionID.Value="2.1";

            facturaXML.CustomizationID = new CustomizationIDType();
            facturaXML.CustomizationID.schemeAgencyName = "PE:SUNAT";
            facturaXML.CustomizationID.Value = "2.0";

            facturaXML.ProfileID = new ProfileIDType();
            facturaXML.ProfileID.schemeAgencyName = "PE:SUNAT";
            facturaXML.ProfileID.schemeURI = "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo51";
            facturaXML.ProfileID.schemeName = "Tipo de Operacion";
            facturaXML.ProfileID.Value = "0101";

            facturaXML.ID = new IDType();
            facturaXML.ID.Value = numeroFactura;

            facturaXML.IssueDate = new IssueDateType();
            facturaXML.IssueDate.Value = Convert.ToDateTime("2019-01-21");
            facturaXML.IssueTime = new IssueTimeType();
            facturaXML.IssueTime.Value = Convert.ToDateTime("00:00:00");
            //-----
            //-----Generando el archivo XML
            XmlWriterSettings setting = new XmlWriterSettings();
            setting.Indent = true;
            setting.IndentChars = "\t";
            string rutaXML = string.Format(@"{0}{1}.xml",
                Path.GetTempPath(),//Se creacion en la carpeta temporal
                numeroFactura);
            using (XmlWriter writer = XmlWriter.Create(rutaXML, setting))
            {
                Type typeToSerialize = typeof(InvoiceType);
                XmlSerializer xs = new XmlSerializer(typeToSerialize);
                xs.Serialize(writer, facturaXML);
            }
            //-----
        }
A partir de la linea 36 se establecen las opciones para la creación del archivo XML.
La linea 47 es la que finalmente crear el archivo XML.

Vamos a ejecutarlo y buscamos en la carpeta temporal


Espero haberlos ayudados, si tiene alguna duda no olvide en preguntar.

Comentarios

  1. Hola amigo, muchas gracias, tengo un error en los Namespace necesarios para el UBL ninguna de estas propiedades esta existe sale error facturaXML.Cac, facturaXML.Cbc, etc

    ResponderBorrar
    Respuestas
    1. Buenos dias, tienes razon me olvide indicar que en la clase ubl generada se debe agregar lo siguiente


      public partial class InvoiceType
      {
      [XmlAttribute(AttributeName = "xmlns")]
      public string Xmlns { get; set; }
      [XmlAttribute(AttributeName = "cac", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Cac { get; set; }
      [XmlAttribute(AttributeName = "cbc", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Cbc { get; set; }
      [XmlAttribute(AttributeName = "ccts", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Ccts { get; set; }
      [XmlAttribute(AttributeName = "ds", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Ds { get; set; }
      [XmlAttribute(AttributeName = "ext", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Ext { get; set; }
      [XmlAttribute(AttributeName = "qdt", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Qdt { get; set; }
      [XmlAttribute(AttributeName = "udt", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Udt { get; set; }
      [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
      public string Xsi { get; set; }

      Borrar
  2. Muchas gracias por tu aporte. No puedo utilizar las clases con Signature, Note, StarDate, EndDate, DespatchDocumentReference. Con los propios de Invoice si lo puedo manejar pero con los anteriores no. Agradezco tu ayuda, sobre como trabajar con estos nodos.

    ResponderBorrar
  3. Buenas amigo estuvo excelente tus tutoriales pero vendria bien un ejemplo con base de datos y jalar algunos datos a la clase y algo que te queria pedir es como puedo llamar mas campos o mostrar otras etiquetas en el ejemplo.

    ResponderBorrar
  4. Buenas tardes podrias apoyarme en la generacion del xml con el c# que los contruistes se esurgente mi correo es : magtmiguelmiguel@gmail.com Nro. cel. 964085844 ó a que telefono podria llamarle para realizar las coordinaciones correspondientes

    ResponderBorrar
  5. Buenos días,
    Como haces para firmar el XML en C# y que los TAG tengan el prefijo "ds", Gracias.

    ResponderBorrar
  6. -Para firmar el XML uso la clase de .net X509Certificate2
    -Para los tag "cbc" ,"cac","ds",etc se agrega en automático cuando serializo la clase eso porque al momento de que se genero la clase con el XSD (ver https://jomsistemas.blogspot.com/2018/03/generar-clase-c-desde-xsd-ubl-21.html) le asigno el namespace, ejemplo:

    [XmlRoot(ElementName = "ProfileID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
    public class ProfileID
    {...
    }

    ResponderBorrar
  7. Muchas gracias por ese aporte, alguna idea para generar el xml completo para colombia.

    ResponderBorrar
    Respuestas
    1. Mi parce, el UBL 2.1 es un estandar mundial, por lo que se debería saber que datos pide la entidad encargada de recibir esta informacion y a partir de eso crear el archivo XML basandose en la clase.

      Borrar
  8. Buen dia, muchas gracias por tus ejemplos, alguna idea para realizar lo mismo en colombia, DIAN

    ResponderBorrar
    Respuestas
    1. Deberias crear las clases con los XSD lo bajas desde
      https://www.dian.gov.co/fizcalizacioncontrol/herramienconsulta/FacturaElectronica/Factura%20Electrnica/Ejemplos/XSD.zip

      Borrar
    2. En aqui peru tenemos Factura en su pais es Nit&DV o que es eso?

      Borrar
  9. Saludos, Excelente aporte, pero me nace una duda, ¿Cual seria el procedimiento para agregar InvoiceLine a el Objeto FacturaXML?

    ResponderBorrar
  10. Gracias por su aporte está bien explicado pero como aria para poner el extencionconten, dónde deberis ir la firma electrónica, gracias por su ayuda de antemano

    ResponderBorrar
  11. Muy buen aporte. Has realizado el mismo proceso con el REGISTRO DE INFORMACIÓN DEL REPORTE FINANCIERO-ECR de la SUNAT, esta pidiendo un archivo XML. Te agradeceria puedas apoyarme.

    ResponderBorrar

Publicar un comentario

Entradas populares