Ris
Ris

Reputation: 1164

.NET and reading xml file

I want to read following xml and populate knowledge tags in a combo box ,itemname tag in a textbox and the rest in combo boxes as well. Any code sample will be very helpful.

<?xml version="1.0" encoding="UTF-8"?>
<swobs>
    <item>
          <knowledge>1</knowledge>
          <knowledge>2</knowledge>
          <knowledge>3</knowledge>
          <knowledge>4</knowledge>
          <itemname>INS Gator Operator</itemname>
          <knowhow>1</knowhow>
          <knowhow>2</knowhow>
          <knowhow>3</knowhow>
          <knowhow>4</knowhow>
          <supervisor>1</supervisor>      
          <supervisor>2</supervisor>      
          <supervisor>3</supervisor>      
          <supervisor>4</supervisor>  
       </item>              
</swobs>

If I try this:

public void LoadXML() { 
    string myXMLfile = Server.MapPath("~/swobs.xml"); 
    DataSet dssowbs = new DataSet(); 
    try 
    { 
          dssowbs.ReadXml(myXMLfile); 
          DropDownList1.DataSource = dssowbs;
          DropDownList1.DataValueField = "knowledge"; 
          DropDownList1.DataBind(); 
     } 
     catch (Exception ex) 
     { 
          Response.Write(ex.ToString()); 
     } 
}

It throws an error.

Upvotes: 0

Views: 1658

Answers (1)

Matt Robinson
Matt Robinson

Reputation: 36

Learn to love LINQ... this is how easy it is:

private void LoadData()
        {
            var allData = XElement.Load("yourdatafile.xml");
            this.comboKnowledge.ItemsSource = allData.Descendants("knowledge").Select(x => x.Value);
            this.textItemName.Text = allData.Descendants("itemname").Select(x => x.Value).SingleOrDefault();
            this.comboKnowHow.ItemsSource = allData.Descendants("knowhow").Select(x => x.Value);
            this.comboSupervisor.ItemsSource = allData.Descendants("supervisor").Select(x => x.Value);
        }

Upvotes: 2

Related Questions