I have this 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>
I need to retrieve the possible responses for an interface:
// 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;
}
}
The result should be a list such as this (for interface ‘Account Lookup’):
Account OK to process
Overridable restriction
But its only returning the first value – ‘Account OK to process’. What is wrong here?
Edit:
I changed my method:
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;
}
But now I get 2 errors on line ‘actionList.Add(action);’:
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'
I suppose the select many is casting the results into something else then strings?
Edit:
To fix the last error:
foreach (var actions in query)
foreach(string action in actions)
actionList.Add(action);
Apparently there is an array within an array here.
This
returns the first “response” element. Use Elements instead.
You then need to select many to get the values.