【问题标题】:Query XML file with LINQ in C#在 C# 中使用 LINQ 查询 XML 文件
【发布时间】:2011-04-29 12:18:55
【问题描述】:

我的 XML 文件有一个 LINQ 查询,它看起来像这样

  IEnumerable<XElement> c = from cli in xEl.Elements(ns + "client") 
                                      where cli.Element(ns+"ID").Value == (((Client)cComboBox.SelectedItem).Id +"")
                                      select cli;

它工作正常.. 接下来我想迭代这些数据,所以我这样做了

           foreach (XElement el in c)
           {

           }

我的xml文件是这样的

 <client>
    <ID>1</ID>
    <name>Andrej</name>

通过该迭代,我想提取客户值(id -> 1,名称 -> Andrej

我的猜测是将el.Element("name").Value 放在循环的中间,但这不起作用... 哦,顺便说一句:我在 C# 中这样做..

我该怎么办?

btw2:如您所见,我是 linq 的新手,所以我认为我在这个方面有点偏离轨道......

如有任何帮助,我们将不胜感激!! TNX!

【问题讨论】:

  • 抱歉,您想获取 id = 1 或 id => 1 的元素吗?

标签: c# xml linq


【解决方案1】:

如果我使用此代码:

  public void Run()
  {
      string fileToLoad = this.GetType().Name + ".xml";

      XElement root = XElement.Load(fileToLoad);

      var selected = from cli in root.Elements("client")
          where cli.Element("ID").Value == "1"
          select cli;

      System.Console.WriteLine("Selected:");
      foreach (var d in selected)
          Console.WriteLine("{0}", d.ToString());

      System.Console.WriteLine("\nitems:");
      foreach (var d in selected)
      {
          Console.WriteLine("id: {0}", d.Element("ID"));
      }
  }

还有这个源数据:

<root>
  <client>
    <ID>1</ID>
    <name>Andrej</name>
  </client>
  <client>
    <ID>2</ID>
    <name>William</name>
  </client>
  <client>
    <ID>3</ID>
    <name>Kate</name>
  </client>
</root>

然后...我得到这个结果:

Selected:
<client>
  <ID>1</ID>
  <name>Andrej</name>
</client>

items:
id: <ID>1</ID>

【讨论】:

    【解决方案2】:

    你可以在一个语句中做到这一点。我在转述你的陈述。只有选择真正改变了。

        var nameIdList = (from cli in client
    where cli.ID == ID
    select new { id=cli.ID, name=cli.name }).ToList();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多