[英]How to write a single LINQ to XML query to iterate through all the child elements & all the attributes of the child elements?
我正在開發asp.net移動應用程序。 我正在使用XML作為數據庫。 我正在查詢XML,以通過.net中的LINQ to XML訪問所需的元素和屬性。 我的XML文件中包含以下內容。
<VALVES>
<VALVE NAME="PWV">
<DISPLAY-NAME>
Production Master Valve
</DISPLAY-NAME>
<COMMANDS USE-TEMPLATE="TRUE" TEAMPLATE-NAME="ValveCommands.xml"></COMMANDS>
</VALVE>
<VALVE NAME="PMV" >
<DISPLAY-NAME>
Production Wing Valve
</DISPLAY-NAME>
<COMMANDS USE-TEMPLATE="TRUE" TEAMPLATE-NAME="ValveCommands.xml"></COMMANDS>
</VALVE>
</VALVES>
在上面的XML文件中,我可以使用以下代碼動態訪問子元素節點“ VALVE”及其屬性“ NAME”,而無需顯式指定屬性的名稱。 因此,由於在子節點“ VALVE”中添加了任何新屬性,因此無需修改現有代碼就可以訪問它。 對於這種邏輯,我正在使用以下代碼。 在以下代碼中,ValvesProperties是哈希表,該哈希表在類“閥門”中定義。
static int count = 0;
List<Valves> LstValves = new List<Valves>();
string AttName = null;
string AttValue = null;
XDocument FieldDef = XDocument.Load(@"F:\Shailesh from user OPC\XML\KK3.xml");
XElement FieldRoot = FieldDef.Element("KK");
count = FieldRoot.Element("FIELD-DEFINITION").Element("VALVES").Elements("VALVE").Count();
Valves[] Valveobj = new Valves[count];
count = 0;
foreach (var element in FieldRoot.Element("FIELD-DEFINITION").Element("VALVES").Elements())
{
Valveobj[count] = new Valves();
foreach (var attribute in element.Attributes())
{
AttName = attribute.Name.ToString();
AttValue = attribute.Value.ToString();
Valveobj[count].ValvesProperties.Add(AttName, AttValue);
LstValves.Add(Valveobj[count]);
}
count++;
}
return LstValves;
對於上面定義的XML部分,我需要類似的邏輯。 在上面的XML中,我想編寫LINQ to XML查詢,它可以訪問'VALVE'節點的NAME屬性( <VALVE NAME="PWV">
),然后它應該訪問'DISPLAY-NODE'( <DISPLAY-NAME> Production Master Valve </DISPLAY-NAME>
),然后它應動態訪問“ COMMAND”節點的所有屬性( <COMMANDS USE-TEMPLATE="TRUE" TEAMPLATE-NAME="ValveCommands.xml"></COMMANDS>
)。 我要動態地進行所有這些操作,而無需顯式指定子節點的名稱及其屬性的名稱(類似於我編寫上述查詢的方式),是否可以使用LINQ to XML編寫這樣的代碼? 如果我們可以用單個邏輯為上述問題編寫代碼,那會更好(類似於我編寫上述查詢的方式)。 您能提供解決上述問題的任何代碼或鏈接嗎?
您可以遍歷所有元素並檢索每個元素的屬性:
var allDescendants = myElement.DescendantsAndSelf();
var allDescendantsWithAttributes = allDescendants.SelectMany(elem =>
new[] { elem }.Concat(elem.Attributes().Cast<XContainer>()));
foreach (XContainer elementOrAttribute in allDescendantsWithAttributes)
{
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.