简体   繁体   中英

How to find a list of Elemenets/Attributes from a specific Element in XML?

How can I query an xml document to return a list of sub-elements/attributes of a specific element.

var entry = from item in doc.Descendants("GROUP")
                        where (string)item.Attribute("meetsMark") == "1"
                        select new
                        {                                
                            code = (string)item.Attribute("code"),                               
                        };

The above returns only the entries that belong to the element GROUP, where the meetsMark attribute is "1". For each of those elements that it returns the code for I need to also get a list of the 'sum' and 'number' for every SUMMARY attribute it contains. Example: I need to have the query return:

code = SECONDARY

sum = SUM1

number = 1

sum = SUM3

number = 3

sum = SUM4

number = 4

code =THIRD

sum = SUM10

number = 1

sum = SUM30

number = 3

sum = SUM40

number = 4

Below is the xml structure.

 <GROUP id="GRP2" code="MAIN" meetsMark="0" <GROUP id="GRP3" code="SECONDARY" meetsMark="1" <ITEMS> <ITEM id="ITM6" <SUMMARY sum="SUM1" number="1" </SUMMARY> </ITEM> <ITEM id="ITM14" <SUMMARY sum="SUM3" number="3" </SUMMARY> </ITEM> <ITEM id="ITM15" <SUMMARY sum="SUM4" number="4" </SUMMARY> </ITEM> </ITEMS> </GROUP> <GROUP id="GRP4" code="THIRD" meetsMark="1" <ITEMS> <ITEM id="ITM95" <SUMMARY sum="SUM10" number="1" </SUMMARY> </ITEM> <ITEM id="ITM96" <SUMMARY sum="SUM30" number="3" </SUMMARY> </ITEM> <ITEM id="ITM97" <SUMMARY sum="SUM40" number="4" </SUMMARY> </ITEM> </ITEMS> </GROUP> </GROUP> 

It will be something like this ... (line feeds omitted for clarity)

var groups = from group in doc.Descendants("GROUP")
            where (string)group.Attribute("meetsMark") == "1"
            select group

var subgroups = from subgroup in groups.Descendants("GROUP")
           where subgroup.Attribute("code").Value == "SECONDARY"
           select subgroup;

foreach( var subgroup in subgroups )
{
   System.Console.WriteFormat( "code = {0}", subgroup.Attribute("code").Value );

   var sums = from summary in subgroup.Descendants("SUMMARY")

   foreach( var sum in sums )
   {
       System.Console.WriteFormat( "sum = {0}", subgroup.Attribute("sum").Value );
       System.Console.WriteFormat( "number = {0}", subgroup.Attribute("number").Value );
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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