2

我有这个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 OK to process'。这里有什么问题?

编辑:
我改变了我的方法:

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'

我想选择的许多人正在将结果转换成其他东西然后是字符串?

编辑:
要修复最后一个错误:

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

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

4

3 回答 3

4

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

返回第一个“响应”元素。请改用元素

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

于 2012-09-12T09:21:42.217 回答
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;
}
于 2012-09-12T09:24:37.530 回答
0
doc.Root.Elements("Interface").Select(e=>new {
 Name = e.Element("Name").Value,
 PossibleResponses = e.Element("PossibleResponses").Elements("Response").select(e2=>e2.Value)
});
于 2012-09-12T09:29:34.330 回答