簡體   English   中英

C#Linq轉XML-返回多個子級

[英]C# Linq to XML - Return multiple children

我有這個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;
    }
}

結果應該是這樣的列表(對於“帳戶查找”接口):
帳戶可以處理
可覆蓋的限制

但它僅返回第一個值-“帳戶可以處理”。 怎么了

編輯:
我更改了方法:

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

顯然這里的數組中有一個數組。

這個

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

返回第一個“響應”元素。 請改用Elements

然后,您需要選擇許多來獲取值。

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;
}
doc.Root.Elements("Interface").Select(e=>new {
 Name = e.Element("Name").Value,
 PossibleResponses = e.Element("PossibleResponses").Elements("Response").select(e2=>e2.Value)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM