【问题标题】:linq query to element w/o foreachlinq 查询到没有 foreach 的元素
【发布时间】:2012-04-27 01:40:53
【问题描述】:

我需要一些有关 LINQ 和 XML 的帮助。我已经阅读了许多文章,但似乎无法找到我正在寻找的内容,因为大多数人都在循环通过结果来获取值。我有以下 XML,我需要首先根据 section name 然后根据 control id 访问特定元素。

<formData>
    <section name="SectionA">
        <control id="Textbox1" type="TextBox">
            <value>Value1</value>
        </control>
        <control id="Textbox2" type="TextBox">
            <value>Value2</value>
        </control>
        <control id="Textbox3" type="TextBox">
            <value>Value2</value>
        </control>
    </section>
    <section name="SectionB" />
    <section name="SectionC" />
    <section name="SectionD" />
    <section name="SectionE" />
</formData>

我正在使用下面的代码来获取我需要的元素。

IEnumerable<XElement> fields = xDocument.Element("formData").Elements("section")
        .Where(m => m.Attribute("name").Value == "SectionA")
        .Single()
        .Elements("control")
        .Where(f => f.Attribute("id").Value == "Control1");

这会产生以下元素:

<control id="Textbox1" type="TextBox">
    <value>Value1</value>
</control>

但是,这就是我所能得到的……我需要三个单独的值,ID、TYPE 和 Value。在不使用 foreach 或嵌套的 foreach 循环的情况下如何解决这个问题?

谢谢

【问题讨论】:

  • 因此,使用匿名类型,我可以通过以下方式访问这些字段: fields.ElementAt(0)fields.FirstOrDefault() 或者是否存在更好的方法?谢谢迈克
  • 对于匿名类型,字段的类型将是 IEnumerable。要访问每个字段,您可以遍历每个控件并访问 Id、Type 和 Value 属性。如果你只想要第一个,调用 fields.FirstOrDefault() 来获取第一个元素。

标签: c# linq linq-to-xml


【解决方案1】:

如果您可以使用匿名类型,您可以这样做:

var fields = xDocument.Element("formData").Elements("section")
    .Where(m => m.Attribute("name").Value == "SectionA")
    .Single()
    .Elements("control")
    .Where(f => f.Attribute("id").Value == "Control1").Select( f => new
{
     Id = f.Attribute("id"),
     Type = f.Attribute("type"),
     Value = f.Element("value").Value
});

【讨论】:

    【解决方案2】:

    试试这个:

    xdoc.Descendants("section")
        .Where(m => m.Attribute("name").Value == "SectionA")
        .Single()
        .Descendants("control")
        .Where(f => f.Attribute("id").Value == "Textbox1")
        .Select(f => new 
                       { Id = f.Attribute("id").Value, 
                         Type = f.Attribute("type").Value, 
                         Value = f.Element("value").Value } );
    

    不过我更倾向于在前半部分使用 XPath:

    xdoc.XPathSelectElements(@"//section[@name=""SectionA""]/control[@id=""Textbox1""]")
        .Select(f => new 
                       { Id = f.Attribute("id").Value, 
                         Type = f.Attribute("type").Value, 
                         Value = f.Element("value").Value } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多