2012-04-24 87 views
0

我想閱讀以下xml和填充知識標籤在一個組合框中,項目名稱標籤在文本框中,其餘的在組合框以及。任何代碼示例都會非常有幫助。.NET和讀取xml文件

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

它拋出一個錯誤。

+2

請出示你已經嘗試 – msarchet 2012-04-24 20:28:38

+0

那麼你嘗試過什麼,和你走多遠? – 2012-04-24 20:28:42

+0

如果我試試這個, public void LoadXML() {0} {0} {0} myXMLfile = Server.MapPath(「〜/ swobs.xml」); DataSet dssowbs = new DataSet(); 嘗試 { dssowbs.ReadXml(myXMLfile); DropDownList1.DataSource = dssowbs; DropDownList1.DataValueField =「知識」; DropDownList1.DataBind(); } catch(Exception ex) { Response.Write(ex.ToString()); } } 它引發錯誤 – Rishi 2012-04-24 20:32:05

回答

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

感謝馬特。爲什麼它在「ItemSource」上顯示錯誤。我不會看到Combo的這種方法。 – Rishi 2012-04-24 21:46:55

+0

你是對的 - 我剛剛從WPF應用程序中拿出了這個例子,但是相同的功能在ASP.NET中可以很好地工作,如下所示: 'DropDownList1.DataSource = allData.Descendants(「knowledge」)。Select x => x.Value); DropDownList1.DataBind();' – 2012-04-24 21:49:11

+0

另一個選擇可能是使用的XmlDataSource,這裏是微軟一個非常有用的鏈接:[鏈接](http://msdn.microsoft.com/en-us/library/system.web。 ui.webcontrols.xmldatasource.xpath.aspx)。 – 2012-04-24 21:54:45