I have an c# class, which inherits from another object, which contains lists of string. the structure is similiar to this:
public class BeneficiaryScreening
{
public int Id { get; set; }
public DateTime ProcessedDate { get; set; }
public string FileName { get; set; }
public int LineCountFile { get; set; }
public int LineCountHits { get; set; }
public string SearchLine { get; set; }
public Entity Entity { get; set; }
}
[Serializable]
public class Entity
{
public string MessageId { get; set; }
public string Id { get; set; }
public string ItemType { get; set; }
public string DateListed { get; set; }
public string Gender { get; set; }
public List<string> Names { get; set; }
public List<string> Countries { get; set; }
}
I populate the class using Dapper, and now need to convert the results to XML to be used with another application.
I can create the document fine, if I'm only using sinlge value fields, but i'm having trouble creating the correct XML for all the list items.
The code I have so far is:
XElement element =
new XElement("Root",
(from bene in xmlDataSet
select new XElement("Item",
new XElement("Id", bene.Id),
new XElement("ProcessedDate", bene.ProcessedDate),
new XElement("FileName", bene.FileName),
new XElement("LineCountFile", bene.LineCountFile),
new XElement("LineCountHits", bene.LineCountHits),
new XElement("Line", bene.SearchLine),
new XElement("Entity",
new XElement("Names",new XElement("name", (from name in bene.Entity.Names
select new XElement("name", name)))))
))
);
My problem, is that everything looks fine, until I start to loop through the Names, which produces the following:
<Entity>
<Names>
<name>
<name>Some Name</name>
<name>Some Name</name>
</name>
</Names>
</Entity>
Can someone point me in the direction, of being able to create the List items, like this:
<Entity>
<Names>
<name>
<value>Some Name</value>
</name>
<name>
<value>Some Name</value>
</name>
</Names>
</Entity>
UPDATE Ok gents, both your examples worked in regards for creating the XML, hence the up vote - however, my external program cant iterate through the subnodes. So I need to create every Name / Country in one XElement, separated with a comma.
new XElement("Entity",new XElement("Names", bene.Entity.Names.Select(name=>
name))),
new XElement("Countries", bene.Entity.Countries.Select(country => country))
So, all I need is a space in between the values
You just need to create a new XElement
called value
for each name:
select new XElement("name", new XElement("value", name))
As an aside, I wouldn't use a query expression for that - I'd just use:
new XElement("Entity",
new XElement("Names",
new XElement("name",
bene.Entity.Names
.Select(name => new XElement("name", new XElement("value", name))
)
)
See more on this question at Stackoverflow