我正在使用 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”屬性,它會回傳屬性的名稱和值:
我認為這個查詢很復雜,有幾個原因。
- XML 樹的深度(嵌套子級)。
- 需要使用屬性值。
如果有人知道如何進行這種型別的 Linq 查詢,請告訴我。
uj5u.com熱心網友回復:
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
元素中,選擇“referenceId”屬性 - 檢查空值(屬性存在)
- 選擇屬性的值(所以你沒有“referenceId = value”,只有值)
uj5u.com熱心網友回復:
好的,我找到了一個可行的解決方案!我只能使用這個查詢符號(我認為它被呼叫)而不是 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;
如果您對此問題有更優雅的解決方案,請告訴我。
uj5u.com熱心網友回復:
找到了這個解決方案:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498016.html