[英]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.