简体   繁体   English

LINQ XML - 在不同层次结构级别选择多个元素

[英]LINQ XML - Select multiple Elements at different hierarchy levels

In this Linq XML query, I want to select(return) multiple elements.在这个 Linq XML 查询中,我想选择(返回)多个元素。 I think multiple elements can often times be stored in a 'new' class, however, I don't know how to do this if they exist on different levels of the tree (hierarchy).我认为多个元素通常可以存储在“新”类中,但是,如果它们存在于树的不同级别(层次结构)中,我不知道该怎么做。 The below Linq query explains the logic I am aiming for, but it doesn't work:下面的 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
                    };

It doesn't matter if the two values are being returned as an IEnumerable of Array[2] or as an IEnumerable<class> , I'm just hoping to be able to access both the values in one place.这两个值是作为 Array[2] 的 IEnumerable 还是作为IEnumerable<class>返回都没有关系,我只是希望能够在一个地方访问这两个值。

Here is a sample of the XML file for reference:以下是供参考的 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>

I would suggest to use XPath for such task:我建议使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM