0

我有以下一段代码

XmlDocument docu = new XmlDocument();
        docu.Load(file);
XmlNodeList lst = docu.GetElementsByTagName("name");
                        foreach (XmlNode n in lst)
                        {
                            string text = n.InnerText;
    var types = doc.Element("program").Element("program-function").Element("function").Descendants("type").Where(x => x.Value == text).Select(c => c.Value).ToArray();
    }

我的xml如下

<program> 
  <program-function> 
    <function>
    <name>add</name> 
    <return-type>double</return-type> 
    <params> 
     <type>double</type> 
     <type-value>a</type-value> 
     <type>double</type> 
     <type-value>b</type-value> 
     <type>string</type> 
     <type-value>c</type-value> 
    </params> 
   <body> return a + b + c; </body> 
</function> 
  <function>
   <name>test</name> 
   <return-type>int</return-type> 
   <params> 
     <type>double</type> 
     <type-value>a</type-value> 
     <type>double</type> 
     <type-value>b</type-value> 
     </params> 
   <body> return a + b; </body> 
  </function> 
 </program-function> 
</program>

我需要能够获得<type>每个的数量<name>

添加的结果应该是 3 =types.count() = 3
测试的结果应该是 2 =types.count() = 2

有什么建议吗?

编辑:如果我想检索里面的每个值types?IE。add应该包含a,并且应该包含b, 。希望将其存储在数组中以便于检索ctestab

4

2 回答 2

1

如何使用 Linq to Xml

 var xDoc = XDocument.Parse(xml);
var functions = xDoc.Descendants("function")
                .Select(f => new
                {
                    Name = f.Element("name").Value,
                    Types = f.Descendants("type").Select(t=>t.Value).ToList(),
                    //Types = f.Descendants("type").Count()
                    TypeValues = f.Descendants("type-value").Select(t=>t.Value).ToList()
                })
                .ToList();
于 2013-04-22T14:00:15.500 回答
0

尝试这个:

XDocument doc = XDocument.Load(your file);
var vals = doc.Element("program").Element("program-function").Elements("function");

var result = vals.Select(i => 
                     new { name = i.Element("name"), 
                           count = i.Elements("type").Count() }
于 2013-04-22T13:59:59.920 回答