2012-04-24 74 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