¿Cómo leer un XML y cargarlo en un GridView con ASP.NET?

¿Cómo leer un XML y cargarlo en un GridView con ASP.NET?

En este artículo voy a explicar cómo leer los datos de un archivo XML y lo mostrare en un GridView todo esto con ASP.Net.

El archivo XML

Primero crearemos un archivo XML denominado Clientes.xml con los registros que se muestran a continuación

<Clientes>
    <Cliente>
        <ClienteID>ALFKI</ClienteID>
        <CompanyName>Alfreds Futterkiste</CompanyName>
        <ContactName>Maria </ContactName>
        <ContactTitle>Agente de ventas</ContactTitle>
        <Address>Obere Str. 57</Address>
        <City>Boise</City>
        <PostalCode>12209</PostalCode>
        <Country>Germany</Country>
        <Phone>030-0074321</Phone>
        <Fax>030-0076545</Fax>
    </Cliente>
    <Cliente>
        <ClienteID>ANATR</ClienteID>
        <CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
        <ContactName>Ana Trujillo</ContactName>
        <ContactTitle>Gerente</ContactTitle>
        <Address>Avda. de la Constitución 2222</Address>
        <City>México D.F.</City>
        <PostalCode>05021</PostalCode>
        <Country>Mexico</Country>
        <Phone>555-4729</Phone>
        <Fax>555-3745</Fax>
    </Cliente>
</Clientes>

Código HTML

El HTML se compone de un control GridView con cuatro columnas que se crearon en el archivo XML. También he especificado OnPageIndexChanging en el GridView, por lo que si el archivo XML tiene un gran número de registros, podemos ver la página de datos inteligente.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="LeerXML_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
                RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
                runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
                <Columns>
                    <asp:BoundField DataField="ClienteID" HeaderText="Id" ItemStyle-Width="80" />
                    <asp:BoundField DataField="ContactName" HeaderText="Name" ItemStyle-Width="150" />
                    <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
                    <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Código de servidor VB.NET

Imports System.Data

Partial Class LeerXML_Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            Me.BindGrid()
        End If
    End Sub
    Private Sub BindGrid()
        Using ds As New DataSet()
            ds.ReadXml(Server.MapPath("Clientes.xml"))
            GridView1.DataSource = ds
            GridView1.DataBind()
        End Using
    End Sub
    Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
        GridView1.PageIndex = e.NewPageIndex
        Me.BindGrid()
    End Sub
End Class

Espero que te sea de utilidad este ejemplo y si tienes algún problema, dudas o sugerencias estoy a tus órdenes. Ayúdanos compartiendo este artículo con tus amigos y contactos.

Puedes descargar el ejemplo en esta liga: https://github.com/jiestrada/LeerXML

Saludos y buen día.

Compartir

Comentarios (3)

  • Cheap Jerseys Responder

    Those whose technicians did a good job can tell these homeowners where to find them. They can help save Mother Earth this way. This gets your meaning out to the largest target audience that will create higher sales and can definitely boost product sales.When deciding how to style your working environment, help it become a lot more ergonomic by positioning your laptop or keep an eye on on your own workplace. This requires anything from gas utilized for business related automobile mileage and World wide web services.

    Monday, July 3, 2017 3:28 PM
  • FitzGibbon Responder

    Having read this I believed it was very enlightening. I appreciate you spending some time and energy to put this article together. I once again find myself spending way too much time both reading and commenting. But so what, it was still worthwhile!

    Monday, August 21, 2017 2:29 AM
  • cartier diver calibre imitation Responder

    I tried the samosas. It is nothing like the authentic samosas. The pastry was so thick and soft. Din’t give a feel of a samosa at all. The shape also was not a samosa shape at all. The samosas shown in the episode looked much better. The filling was ok but the spices tasted uncooked. It was over spiced too. There are so many better frozen samosas in shops. This was not to my liking at all.The word authentic should be taken out. The samiosas were overpraised in the show. Will not buy them ever again. A big waste of money.

    Tuesday, November 14, 2017 8:47 PM

Animate deja un comentario!!!

Eres un humano?

Últimos Tweets

Contáctanos

  • Dirección: Plutarco Elias Calles 243, Granjas México, Iztacalco, DF.

  • Teléfono:55-2712-3820 o 55-4164-9484

  • Email: info@developerji.com