【问题标题】:C# Linq over XML => Lambda ExpressionC# Linq over XML => Lambda 表达式
【发布时间】:2010-03-05 20:30:18
【问题描述】:

我有一个 xml 文档,其中包含以下内容:

- <LabelFieldBO>
  <Height>23</Height> 
  <Width>100</Width> 
  <Top>32</Top> 
  <Left>128</Left> 
  <FieldName>field4</FieldName> 
  <Text>aoi_name</Text> 
  <DataColumn>aoi_name</DataColumn> 
  <FontFamily>Arial</FontFamily> 
  <FontStyle>Regular</FontStyle> 
  <FontSize>8.25</FontSize> 
  <Rotation>0</Rotation> 
  <LabelName /> 
  <LabelHeight>0</LabelHeight> 
  <LabelWidth>0</LabelWidth> 
  <BarCoded>false</BarCoded> 
  </LabelFieldBO>

我已经弄清楚如何找到 LabelName = 'container' 的元素。但我不太熟悉 lambda 表达式,想知道如何访问我的 LINQ 结果中的信息。 Lambda 表达式也可能不是要走的路。我愿意接受任何建议。

var dimensions = from field in xml.Elements("LabelFieldBO")
                             where field.Element("LabelName").Value == "container"
                             select field;

谢谢。

编辑:我想弄清楚的是如何从 LabelName = "container" 的 XML 中获取 LabelHeight 和 LabelWidth

【问题讨论】:

  • 不清楚你想做什么,请你描述得更准确一点。可以使用您期望的结果样本。

标签: c# xml linq lambda


【解决方案1】:

以下代码创建一个新的匿名对象,其中包含标签名称、宽度和高度。

var result = doc.Elements("LabelFieldBo")
                 .Where(x => x.Element("LabelName").Value == "container")
                 .Select(x =>
                     new { 
                         Name = x.Element("LabelName").Value,
                         Height = x.Element("LabelHeight").Value,
                         Width = x.Element("LabelWidth").Value
                 }
             ); 

【讨论】:

    【解决方案2】:
    from field in xml.Elements("LabelFieldBO")  
    where field.Element("LabelName").Value == "container"  
    select new   
    {  
        LabelHeight = field.Element("LabelHeight").Value,  
        LabelWidth = field.Element("LabelWidth").Value  
    }
    

    这将返回具有两个属性(LabelWeight 和 LabelWidth)的匿名类型的 IEnumerable。 IEnumerable 中的每个对象都代表一个 LabelFieldB0,LabelName = "container"。

    因此,您可以通过以下方式“获取”您的数据:

    var containerLabels =   
        from field in xml.Elements("LabelFieldBO")  
        where field.Element("LabelName").Value == "container"  
        select new   
        {  
            LabelHeight = field.Element("LabelHeight").Value,  
            LabelWidth = field.Element("LabelWidth").Value  
        } 
    
    foreach (var containerLabel in containerLabels)  
    {  
        Console.WriteLine(containerLabel.LabelHeight + " "
            + containerLabel.LabelWidth);  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多