C#中针对XML的Linq查询语句转换为Lambda表达式

3

我有一个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;

谢谢。

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


不太清楚您想要做什么,请您能否更详细地描述一下,最好能提供您期望得到的结果样例。 - AxelEckenberger
2个回答

5
以下代码创建一个包含标签名称、宽度和高度的新匿名对象。
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
                 }
             ); 

1
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中的每个对象都表示具有LabelName =“container”的LabelFieldB0。
因此,您可以通过以下方式访问数据:
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);  
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接