Reputation: 163
I have an XML with a List nested and I need all properties inside my class object.
Class:
public class Process
{
public Process()
{
Progresses = new List<Progress>();
}
public string Code{ get; set; }
public List<Progress> Progresses { get; set; }
}
public class Progress
{
public string Text { get; set; }
public string ProgressDate { get; set; }
}
XML:
<PROCESSES>
<Process>
<Number>8754639647985</Number>
<Progress>
<Date>09/11/2013</Date>
<Text>Lorem lalal asdf</Text>
<Date>10/11/2015</Date>
<Text>Lorem lal</Text>
</Progress>
<Progress>
<Date>09/12/2016</Date>
<Text>Lorem aqwq</Text>
<Date>10/11/2017</Date>
<Text>Lorem qw</Text>
</Progress>
</Process>
<Process>
<Number>1121321321321321</Number>
<Progress>
<Date>09/11/2013</Date>
<Text>Lorem lalal asdf</Text>
<Date>10/11/2015</Date>
<Text>Lorem lal</Text>
</Progress>
<Progress>
<Date>09/12/2016</Date>
<Text>Lorem aqwq</Text>
<Date>10/11/2017</Date>
<Text>Lorem qw</Text>
</Progress>
</Process>
</PROCESSES>
Until now I have this Linq:
var _procs =
from proc in xml.Root.Elements("Process")
select new Process()
{
Code = (string)proc.Element("Number"),
Progresses = proc.Elements("Progress")
.Select(c => new Progress
{
Text = (string)c.Element("Text"),
ProgressDate = (string)c.Element("Date")
}).ToList()
};
But with this, I have one register to each Progress tag, instead of a List of Progresses! My biggest question is, how can I read the XML and set as the Class PROCESS, I need all the PROGRESS tags inside the List on my PROCESS object.
UPDATE: With this Linq, I'm getting just the first element of Progress nested nodes. How can I do that (better if using Lambda)? Thanks a lot!!!
Upvotes: 2
Views: 1494
Reputation: 8591
As i mentioned in the comment to the question Progress
class have to be declared as public
.
Another issue is: Num
is not a member of Progress
class!
[EDIT]
var query = xdoc.Descendants("Process")
.Select(x=> new Process
{
Code = x.Element("Number").Value,
Progresses = x.Descendants("Progress")
.SelectMany((ele, j)=> ele.Elements("Date").Select((a, i)=>new{Date = a.Value, Index = i+(j*10)}))
.Join(x.Descendants("Progress").SelectMany((ele, j)=> ele.Elements("Text").Select((a, i)=>new{Text = a.Value, Index = i+(j*10)})),
dat => dat.Index,
tex => tex.Index,
(dat, tex) => new {D = dat, T = tex})
.Select(jdata=> new Progress
{
//Index = jdata.D.Index,
ProgressDate = jdata.D.Date,
Text = jdata.T.Text
}).ToList<Progress>()
});
Above query returns IEnumerable<Process>
with the list of Progresses
.
Code Progresses
8754639647985 Lorem lalal asdf 09/11/2013
Lorem lal 10/11/2015
Lorem aqwq 09/12/2016
Lorem qw 10/11/2017
1121321321321321 Lorem lalal asdf 09/11/2013
Lorem lal 10/11/2015
Lorem aqwq 09/12/2016
Lorem qw 10/11/2017
Upvotes: 1