【问题标题】:Parsing XML problem with LINQ使用 LINQ 解析 XML 问题
【发布时间】:2011-09-05 13:31:51
【问题描述】:

我想从 XML 文件中获取一些值并使用 LINQ 将它们插入到 ListBox 中。我哪里错了?

<?xml version="1.0" encoding="UTF-8"?>
<tells> 
    <defindividual name="name1"/>
    <instanceof>
      <individual name="name1"/>
      <catom name="value"/>
    </instanceof>

    <defindividual name="name2"/>
    <instanceof>
      <individual name="name2"/>
      <catom name="value"/>
    </instanceof>

    <defindividual name="name3"/>
    <instanceof>
      <individual name="name3"/>
      <catom name="otherValue"/>
    </instanceof>
</tells> 

代码隐藏:

protected void Button1_Click(object sender, EventArgs e)
{
    XDocument owlXML = XDocument.Load(Server.MapPath("App_Data\\myFile.xml"));

    var items = from item in owlXML.Descendants("instanceof")
                where item.Element("catom").Attribute("name").Value == "value"
                select new
                {
                    catom = item.Element("catom").Attribute("name").Value
                };

    foreach (var item in items) 
    {
        //ListBox1.DataSource = item;
        //ListBox1.DataBind();

        ListBox1.Items.Add(item.catom);
    }        
}

【问题讨论】:

  • 问题是我的 ListBox1 总是空的。我尝试用 List 项目填充它并且它有效,但是当我尝试用 IEnumerable 项目填充它时没有任何反应。
  • 我更新了我的答案,添加了ToArray()。您也可以使用 `ToList() 但不需要由此产生的开销。

标签: c# asp.net linq .net-3.5 linq-to-xml


【解决方案1】:
var names = from item in owlXML.Descendants("instanceof")
            let name = item.Element("catom").Attribute("name")  // cache
            where name.Value == "value"
            select name;

foreach (var name in names.ToArray()) 
{
    ListBox1.Items.Add(name);
}

var items = from item in owlXML.Descendants("instanceof")
            let name = item.Element("catom").Attribute("name")  // cache
            where name.Value == "value"
            select new { catom = name }; // if ListBox is configured to field="catom"

ListBox1.DataSource = items.ToArray(); // items!
ListBox1.DataBind();

【讨论】:

  • dl.kr.org/dig/2003/02/lang"> - 我发现当我将这个“uri”添加到tells标签时,LINQ查询是空的。我想出了点问题,但是什么以及为什么?
  • @Maistora:那是命名空间,见MSDN,尤其是this article
猜你喜欢
  • 2012-08-28
  • 2011-06-13
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
相关资源
最近更新 更多