ASP.NET - Importar datos xml

 
Vista:
sin imagen de perfil

Importar datos xml

Publicado por brian alexis (1 intervención) el 12/10/2022 05:53:43
Hola a todos! un gusto estar por este foro, soy nuevo en esto y ando aprendiendo, tengo algunas dudas con mi codigo ojala me puedan ayudar a mostrarme donde estoy cometiendo mi error, de antemano gracias.

Les comento, estoy creando una pagina web con visual studio y mi proyecto trata de subir un archivo CFDI 3.3 (Xml) y guardar algunos datos dentro de una tabla en sql server. Tengo el siguiente codigo que he investigado en varias paginas pero no encuentro el fallo ya que no me lo marca y simplemente no me sube nada a las tablas. adjunto el codigo y un ejemplo del tipo de xml que intento leer. indice


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Xml.Linq;
 
namespace tessst2
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Populate();
                IbIMessage.Text = "Current Database Data!";
            }
        }
 
        private void Populate()
        {
            using (ProyectoEntities4 dc = new ProyectoEntities4())
            {
                gvData.DataSource = dc.Cfdi_Conceptos.ToList();
                gvData.DataBind();
            }
        }
 
        protected void BtnImport_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile.ContentType == "text/xml" || FileUpload1.PostedFile.ContentType == "application/xml")
            {
                try
                {
                    string FileName = Path.Combine(Server.MapPath("/Uploadxml"), Guid.NewGuid().ToString() + ".xml");
                    FileUpload1.PostedFile.SaveAs(FileName);
                    XDocument xDoc = XDocument.Load(FileName);
                    List<Cfdi_Conceptos> conceptos = xDoc.Descendants("cfdi:Concepto").Select(d => new Cfdi_Conceptos
                    {
                        ClaveProdServ = d.Element("ClaveProdServ").Value,
                        NoIdentificacion = d.Element("NoIdentificacion").Value,
                        Cantidad = d.Element("Cantidad").Value,
                        ClaveUnidad = d.Element("ClaveUnidad").Value,
                        Unidad = d.Element("Unidad").Value,
                        Descripcion = d.Element("Descripcion").Value,
                        ValorUnitario = d.Element("ValorUnitario").Value,
                        Importe = d.Element("Importe").Value
                    }).ToList();
 
                    using (ProyectoEntities4 dc = new ProyectoEntities4())
                    {
                        foreach (var i in conceptos)
                        {
                            var v = dc.Cfdi_Conceptos.Where(a => a.ClaveProdServ.Equals(i.ClaveProdServ)).FirstOrDefault();
                            if (v != null)
                            {
                                v.NoIdentificacion = i.NoIdentificacion;
                                v.Cantidad = i.Cantidad;
                                v.ClaveUnidad = i.ClaveUnidad;
                                v.Unidad = i.Unidad;
                                v.Descripcion = i.Descripcion;
                                v.ValorUnitario = i.ValorUnitario;
                                v.Importe = i.Importe;
                            }
                            else
                            {
                                dc.Cfdi_Conceptos.Add(i);
                            }
                        }
                        dc.SaveChanges();
                    }
                    Populate();
                    IbIMessage.Text = "Import Done Succesfully!";
 
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Juan Arturo Gomez
Val: 6
Ha aumentado su posición en 5 puestos en ASP.NET (en relación al último mes)
Gráfica de ASP.NET

Importar datos xml

Publicado por Juan Arturo Gomez (7 intervenciones) el 03/11/2022 07:25:33
Una vez asegurado que tu archivo este en la ruta (en VB necesitaras hacer la conversion a C#):

leerArchivoXML_enDisco_y_Parsear = ""
Dim doc As New System.Xml.XmlDocument

doc.Load(nombreArchivoDestino)
'//Obtenemos el nodo raiz del documento.
Dim comprobante As XmlElement = doc.DocumentElement

Dim cuentaDetalle As Integer = 0
'------------------------------------------------
' Recuperamos conceptos
'------------------------------------------------
Dim nodoConceptos As XmlNode = comprobante.Item("cfdi:Conceptos")
If Not nodoConceptos Is Nothing Then

Dim cantidadRenglonesDetalle As Integer = nodoConceptos.ChildNodes.Count
Dim tmpCFDI_concepto As String = ""

If cantidadRenglonesDetalle > 0 Then
cuentaDetalle = 0
For cuentaDetalle = 0 To nodoConceptos.ChildNodes.Count - 1
' AQUI SOLO ME INTERESA RECUPERAR EL CONCEPTO... pero aplicara para resto de atributes
Dim nodoConceptoIndividual As XmlNode = nodoConceptos.ChildNodes(cuentaDetalle)
With nodoConceptoIndividual
If Not .Attributes("Descripcion") Is Nothing Then ' V3.3 viene como "Descripcion"
If tmpCFDI_concepto <> "" Then tmpCFDI_concepto = tmpCFDI_concepto & vbCrLf
tmpCFDI_concepto = tmpCFDI_concepto & .Attributes.GetNamedItem("Descripcion").Value()
End If

If Not .Attributes("descripcion") Is Nothing Then
If tmpCFDI_concepto <> "" Then tmpCFDI_concepto = tmpCFDI_concepto & vbCrLf
tmpCFDI_concepto = tmpCFDI_concepto & .Attributes.GetNamedItem("descripcion").Value()
End If

End With

Next


End If ' de cantidad renglonesdetalle>0
End If
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar