将所有XML文件标记加载到DropDownList中

时间:2009-08-26 12:07:52

标签: c# asp.net xml

我是初学者,我想选择一个XML文件并将其元素(即包含<item><title>等标记的文件)加载到DropDownList

在单独的TextBox中,它应该计算并显示特定标记或元素的存在次数。

当从DropDownList中选择特定元素时,内容,描述(包括该元素中的子元素)应显示在TextBox中。

我使用ASP.NET和C#。

............................................... .................................................. ...............

对于所有已阅读并回复我的答案的人来说,Thanx很多。 我只使用ASP.Net 3.5。

我会解释.........

XML文件的示例 XML文件

 <Persons>

    帕克斯顿     慕尼黑     29           麦克风     奥兰多     33           艾拉     LA     13           扎克     慕尼黑     32           英格丽     奥斯陆     63   

首先,我浏览并选择此XML文件。

其次,将Xml标记加载到DropDownlist中。        即。下拉列表应包含人员,姓名,城市和人员。年龄。

   Now on selecting say **Person** the textbox should Display Message as "The XML File has: 5 Person tags" and SHould display all the Contents under Person tags including its subtags.

例如:

<Person>
<Name>Paxton</Name>
<City>Munich</City>
<Age>29</Age>

       麦克风     奥兰多     33           艾拉     LA     13           扎克     慕尼黑     32           英格丽     奥斯陆     63   

这样它也应该显示任何其他标签,例如姓名,城市,年龄,人。

      In the same way for any other XML File that is selected.

我的pblm是,我无法将XML 标记加载到下拉列表中。

Plz帮帮我

1 个答案:

答案 0 :(得分:1)

你的问题不是100%明确,但我们可以试一试。

首先让我们创建一个具有ElementName属性和XElement属性的类,该属性覆盖ToString()方法,我们可以使用它来填充下拉列表...

  public class displayclass
  {
    public string ElementName { get; set; }
    public XElement Element { get; set; }
    public override string ToString()
    {
      return ElementName;
    }
  }

然后我们可以轻松地将元素添加到Combobox中,并使用元素名称作为文本,就像这样

//Some Sample Xml
  XElement xe = new XElement("Root",
    new XElement("Customer",
      new XAttribute("Name", "John Smith"),
      new XAttribute("CreditLimit", 1500)),
    new XElement("Employee",
      new XAttribute("Name", "Fred Nerk")),
    new XElement("Employee",
      new XAttribute("Name", "Sally Silverton")));

  var elemList = from x in xe.Elements()
                 select new displayclass { ElementName = x.Name.ToString(), Element = x };
  foreach (var item in elemList)
  {
    comboBox1.Items.Add(item);
  }

现在让我们使用列表中的group by子句将元素的数量添加到文本框中......

  var qry = from dispObj in elemList
            group dispObj by dispObj.ElementName;
  StringBuilder sb = new StringBuilder();
  foreach (var grp in qry)
  {
    int count = grp.Count();
    sb.AppendLine(string.Format("{0}({1})", grp.Key,grp.Count()));
  }
  textBox1.Text = sb.ToString();

最后让我们为Combobox的选定索引更改事件添加一个事件处理程序,以显示元素的内容......

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  displayclass disp = comboBox1.SelectedItem as displayclass;
  if (disp != null)
  {
    textBox2.Text = disp.Element.ToString();
  }
}

我认为这符合您上面列出的要求。