[英]Linq to Select a Parent based on Attribute of a Nested Child
我正在使用 System.Xml.Linq 以便从此 XML 文件中获取我需要的信息。 我需要得到一个在子元素中具有正确 entityType 的 referenceId 的列表。
这是我正在使用的 XML 文件的示例。
<PropertySetBindings>
<PropertySetBind referenceId="assemblies">
<Rules>
<Include entityType="IfcElementAssembly" subtypes="true" />
</Rules>
</PropertySetBind>
<PropertySetBind referenceId="beam_common">
<Rules>
<Include entityType="IfcBeam" subtypes="false" />
</Rules>
</PropertySetBind>
<PropertySetBind referenceId="column_common">
<Rules>
<Include entityType="IfcColumn" subtypes="false" />
</Rules>
</PropertySetBind>
这是我能想到的最好的 Linq 查询,但它没有返回任何内容。 一旦我尝试查询属性,似乎什么都不起作用
var bindings = xElement.Elements("PropertySetBindings")
.Elements("PropertySetBind")
.Where(x => x.Elements("Rules")
.Elements("Include")
.Attributes("entityType").FirstOrDefault().Equals("IfcBeam"))
.Select(x => x.Attribute("referenceId"));
我认为这可能与访问属性的值有关。 Attributes("entityType").Value 没有属性另外,如果我尝试简单地返回所有“entityType”属性,它会返回属性的名称和值:
我认为这个查询很复杂,有几个原因。
如果有人知道如何进行这种类型的 Linq 查询,请告诉我。
var referenceIds = xElement.Element("PropertySetBindings")
.Elements("PropertySetBind")
.Where(x => x.Elements("Rules")
.Any(r => r.Elements("Include")
.Any(i => i.Attributes("entityType")
.Any(a => a.Value == "IfcBeam")
)
)
)
.Select(x => x.Attribute("referenceId"))
.Where(x => x != null)
.Select(x => x.Value);
它的工作原理如下:
PropertySetBindings
元素PropertySetBind
绑定孩子Rules
元素的子级,这些元素具有Include
具有entityType
属性的元素,其值为“IfcBeam”。PropertySetBind
元素中,select 的“referenceId”属性好的,我找到了一个可行的解决方案。 我只能使用这个查询符号(我认为它被称为)而不是 Lambda 符号来让它工作。 这允许访问属性的值
var bindings = from binding in xElement.Elements("PropertySetBindings")
from bind in binding.Elements("PropertySetBind")
from ru in bind.Elements("Rules")
from inc in ru.Elements("Include")
where (string)inc.Attribute("entityType") == "IfcBeam"
select bind.Attribute("referenceId").Value;
如果您对此问题有更优雅的解决方案,请告诉我。
找到了这个解决方案:
var bindings = xElement.Elements("PropertySetBindings")
.Elements("PropertySetBind")
.Where(x => x.Elements("Rules").FirstOrDefault()
.Elements("Include").FirstOrDefault()
.Attributes("entityType").FirstOrDefault().Value.Equals("IfcBeam"))
.Select(x => x.Attributes("referenceId").FirstOrDefault().Value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.