.NET和读取xml文件

时间:2012-04-24 20:27:36

标签: .net xml

我想阅读以下xml并在组合框中填充知识标记,在文本框中填充 itemname 标记,其余在组合框中。任何代码示例都非常有用。

<?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>

如果我试试这个:

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()); 
     } 
}

它会抛出错误。

1 个答案:

答案 0 :(得分:2)

学会爱LINQ ......这就是多么容易:

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);
        }