Home > Software engineering >  ASP.NET C# bind XML data to GridView
ASP.NET C# bind XML data to GridView

Time:03-29

Sorry if this question has already been asked, I am having a hard time finding an answer.

I am using ASP.NET C# GridView to bind data from an XML file. However, the data will only bind to the GridView if I remove the root <BookCollection> element. Is there any way to keep this and still bind the nested data?

<?xml version="1.0" encoding="UTF-8"?>
<BookCollection>
   <collection>
      <Books>
         <id>1</id>
         <bookName>The Bible</bookName>
         <unitprice>50</unitprice>
         <quantity>1</quantity>
      </Books>
   </collection>
</BookCollection>

C# Code

DataSet ds= new DataSet();
ds.ReadXml(Server.MapPath("XML file path"));
GridView1.DataSource = ds;
GridView1.DataBind();

I have tried manually using the <asp:BoundField DataField="id"/> in the GridView, still no luck.

Appreciate the help.

CodePudding user response:

If you need only the Books, then you can achieve with this,

GridView1.DataSource = ds.Tables["Books"];
  • Related