LINQ XML -选择不同层次级别的多个元素

9rygscc1  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(112)

In this Linq XML query, I want to select(return) multiple elements. 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:

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.
Here is a sample of the XML file for reference:

<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>
kqlmhetl

kqlmhetl1#

我建议使用XPath来完成这样的任务:

var propertyNames = xElement
    .SelectNodes("/PropertySetDefinitions/PropertySet/Properties/Property/PropertyValue/GetValue/TemplateName")
    .OfType<XmlNode>()
    .Select(x => x.InnerText)
    .ToList();

相关问题