简体   繁体   English

如何从XML中的特定元素中查找列表符/属性?

[英]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. 如何查询xml文档以返回特定元素的子元素/属性列表。

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". 上面的代码仅返回属于元素GROUP的条目,其中MeetsMark属性为“ 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. 对于它返回代码的每个元素,我还需要获取其中包含的每个Summary属性的'sum'和'number'列表。 Example: I need to have the query return: 示例:我需要查询返回:

code = SECONDARY 代码=次要

sum = SUM1 总和= SUM1

number = 1 数= 1

sum = SUM3 总和= SUM3

number = 3 数= 3

sum = SUM4 总和= SUM4

number = 4 数= 4

code =THIRD 代码= THIRD

sum = SUM10 总和= SUM10

number = 1 数= 1

sum = SUM30 总和= SUM30

number = 3 数= 3

sum = SUM40 总和= SUM40

number = 4 数= 4

Below is the xml structure. 下面是xml结构。

 <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 );
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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