C#Linq to XML - 返回多个子节点

时间:2012-09-12 09:12:12

标签: c# linq-to-xml

我有这个xml:

<?xml version="1.0" encoding="utf-8" ?>
<Interfaces>
  <Interface>
    <Name>Account Lookup</Name>
    <PossibleResponses>
      <Response>Account OK to process</Response>
      <Response>Overridable restriction</Response>
    </PossibleResponses>
  </Interface>
  <Interface>
    <Name>Balance Inquiry</Name>
    <PossibleResponses>
      <Response>Funds available</Response>
      <Response>No funds</Response>
    </PossibleResponses>
  </Interface>
</Interfaces>

我需要检索接口的可能响应:

// Object was loaded with XML beforehand    
public class Interfaces : XElement {
    public List<string> GetActionsForInterface(string interfaceName) {
        List<string> actionList = new List<string>();
        var actions = from i in this.Elements("Interface")
                      where i.Element("Name").Value == interfaceName
                      select i.Element("PossibleResponses").Element("Response").Value;

        foreach (var action in actions)
            actionList.Add(action);

        return actionList;
    }
}

结果应该是这样的列表(对于界面'Account Lookup'):
帐户可以处理
可覆盖的限制

但它只返回第一个值 - '帐户可以处理'。这有什么不对?

编辑:
我改变了方法:

public List<string> GetActionsForInterface(string interfaceName) {
    List<string> actionList = new List<string>();
    var actions = from i in this.Elements("interface")
                  where i.Element("name").Value == interfaceName
                  select i.Element("possibleresponses").Elements("response").Select(X => X.Value);

    foreach (var action in actions)
        actionList.Add(action);

    return actionList;
}

但现在我在第'actionList.Add(action);':

行上遇到2个错误
The best overloaded method match for System.Collections.Generic.List<string>.Add(string)' has some invalid arguments 
Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<char>' to 'string'

我认为select many会将结果转换为其他字符串而不是字符串?

编辑:
要修复上一个错误:

    foreach (var actions in query)
        foreach(string action in actions)
            actionList.Add(action);

显然这里的数组中有一个数组。

3 个答案:

答案 0 :(得分:4)

select i.Element("PossibleResponses").Element("Response")

返回第一个“response”元素。请改用Elements

然后您需要选择多个来获取值。

答案 1 :(得分:0)

static List<string> GetActionsForInterface(string interfaceName)
{
  var doc = XDocument.Parse(xml);
  List<string> actionList = new List<string>();
  var actions = doc.Root
    .Elements("Interface")
    .Where(x => x.Element("Name").Value == interfaceName).
    Descendants("Response").Select(x => x.Value);

  foreach (var action in actions)
    actionList.Add(action);

  return actionList;
}

答案 2 :(得分:0)

doc.Root.Elements("Interface").Select(e=>new {
 Name = e.Element("Name").Value,
 PossibleResponses = e.Element("PossibleResponses").Elements("Response").select(e2=>e2.Value)
});