[英]LINQ XML - Select multiple Elements at different hierarchy levels
在这个 Linq XML 查询中,我想选择(返回)多个元素。 我认为多个元素通常可以存储在“新”类中,但是,如果它们存在于树的不同级别(层次结构)中,我不知道该怎么做。 下面的 Linq 查询解释了我的目标逻辑,但它不起作用:
IEnumerable<string> propertyNames = from psetdefs in xElement.Elements(ns + "PropertySetDefinitions")
from pset in psetdefs.Elements(ns + "PropertySet")
where (string)pset.Attribute("referenceId").Value == set
from props in pset.Elements(ns + "Properties")
from prop in props.Elements(ns + "Property")
from propValue in prop.Elements(ns + "PropertyValue")
from valCon in propValue.Elements(ns + "ValueConversion").DefaultIfEmpty(propValue)
from getValue in valCon.Elements(ns + "GetValue")
from templateName in getValue.Elements()
select new
{
templateName.Value,
prop.Elements(ns + "Name").Value
};
这两个值是作为 Array[2] 的 IEnumerable 还是作为IEnumerable<class>
返回都没有关系,我只是希望能够在一个地方访问这两个值。
以下是供参考的 XML 文件示例:
<PropertySetDefinitions>
<PropertySet referenceId="Common">
<Name>Tekla Common</Name>
<Description>Common Properties to Shared building elements</Description>
<Properties>
<Property xsi:type="PropertySingleValueType" optional="true">
<Name>Class</Name>
<PropertyValue xsi:type="StringValueType" stringType="IfcLabel">
<GetValue xsi:type="TemplateVariableType">
<TemplateName>CLASS_ATTR</TemplateName>
</GetValue>
</PropertyValue>
</Property>
</Properties>
</PropertySet>
</PropertySetDefinitions>
我建议使用 XPath 来完成这样的任务:
var propertyNames = xElement
.SelectNodes("/PropertySetDefinitions/PropertySet/Properties/Property/PropertyValue/GetValue/TemplateName")
.OfType<XmlNode>()
.Select(x => x.InnerText)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.