Reputation: 105
I have written linq code so I can read childnodes from the a parent node. I m getting the both the child node values, but it appear as one long string. How to split the values?
This is my XML calling function:
var wsinputs = new List<string>();
wsinputs = readXMLInput(2);
This is my function:
public List<string> readXMLInput(int seq)
{
XElement xelement = XElement.Load(@"C:\Users\XXXXX\XXXX\selection.xml");
IEnumerable<XElement> selectedServiceList = xelement.Elements();
var inputtype = new List<string>();
int countnum = selectedServiceList.Descendants("seq").Count();
// for (int x = 1; x <= countnum; x++)
// {
IEnumerable<string> serviceinputs = from servinput in xelement.Elements("Service")
let inp = (string)servinput.Element("inputs")
orderby inp
// where (string)servinput.Element("seq") == seq.ToString()
select inp;
foreach (string zp in serviceinputs)
{
inputtype.Add(zp);
}
//}
return inputtype;
}
This is the output i get:
System.IntSystem.Int
I need to get :
System.Int
System.Int
The node values should be separated.
This is my xml:
<SelectedService>
<Service>
<servicename>updatemapInt</servicename>
<seq>1</seq>
<serviceURL>http://XXX.XXXX.net/Service1.svc?wsdl</serviceURL>
<inputs>
<input>System.Int</input>
<input>System.Int</input>
</inputs>
<Output>System.String</Output>
</Service>
<Service>
Upvotes: 1
Views: 236
Reputation: 760
When you do servinput.Element("inputs")
, you get at once all the content of the node <inputs>
(that's why you get the System.IntSystem.Int
single string as output). In order to get the <input>
nodes separated, you can do something like this:
IEnumerable<string> serviceinputs = from inputs in xelement.Elements("Service")
.Elements("inputs")
.Elements("input")
orderby inputs.Value
select inputs.Value;
If you want to do some more filtering, you can do it easily:
IEnumerable<string> serviceinputs = from servinput in xelement.Elements("Service")
where (string)servinput.Element("seq") == seq.ToString()
from inputs in servinput.Elements("inputs").Elements("input")
orderby inputs.Value
select inputs.Value;
Upvotes: 0
Reputation: 89285
Firstly, you can call ToList()
to have the LINQ query return List<T>
instead of IEnumerable<T>
. Then for the main question, you can either use double form
clause like so :
List<string> serviceinputs = (from service in xelement.Elements("Service")
from servinput in service.Element("inputs").Elements("input")
let inp = (string)servinput
orderby inp
select inp).ToList();
Or modify the single from
clause to return individual <input>
value separately :
List<string> serviceinputs = (from servinput in xelement.Elements("Service")
.Elements("inputs")
.Elements("input")
let inp = (string)servinput
orderby inp
select inp).ToList();
output :
System.Int
System.Int
Upvotes: 1