【问题标题】:How to use Linq to parse through XML easly - Need some sample code [closed]如何使用 Linq 轻松解析 XML - 需要一些示例代码 [关闭]
【发布时间】:2014-06-14 04:43:49
【问题描述】:

我在我的 SQL Server 中使用 XML Auto 来查询数据。我想知道如何最好地解析它提供的数据。

我的最终目标是提供一个项目列表及其值,但我不知道有多少列或列的名称将是什么,直到至少在运行时从 SQL 中提取数据。

这是一个示例 XML

  <animals>
    <animal name="Pig">
      <meat>
        <name>Prosciutto</name>
      </meat>
      <meat>
        <name>Speck</name>
      </meat>
    </animal>
    <animal name="Cow">
      <meat>
        <name>Clod</name>
      </meat>
      <meat>
        <name>Brisket</name>
      </meat>
      <meat>
        <name>Tri-tip</name>
      </meat>
    </animal>
    <animal name="Chicken">
      <meat>
        <name>Drumstick</name>
      </meat>
    </animal>
  </animals>

如何在列表中显示它,并执行 Linq2SQL(或 Linq2XML)?

【问题讨论】:

  • 为什么首先使用 LINQ?一定要吗?
  • 你的专栏是什么?那个动物。您希望您的列表按动物和肉类分组吗?

标签: c# asp.net sql sqlxml


【解决方案1】:

选择列表

var q = from x in doc.Descendants()
        select x.Value;

选择特定的节点,例如动物,做doc.Descendants("animal")

选择特定的值,例如动物的名字做select x.Attribute("name").Value

演示:https://dotnetfiddle.net/TdCWjE

【讨论】:

  • 如何更深入一层?
  • XDocument doc = XDocument.Parse(s); var q = from x in doc.Descendants("animal") select x; foreach(var x in q) { Console.WriteLine(x.Element("meat").Value); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2013-01-03
  • 2011-11-10
  • 2010-12-28
相关资源
最近更新 更多