Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone!

I have a question regarding LinQ to XML and iterating through a list.

This is my code so far:

C#
new XElement("caption", data.ToList().Select(x => x))


What this is doing is printing an XElement statement with everything in the list "data". What my intent is is to have one XElement statement per element in the list (sort of recursive fashion). Can anyone shed some light as to what I'm doing wrong?

Thanks everyone!
Posted

1 solution

You need to iterate through data and yield an XElement for each item.
C#
var result = new XElement("captions", data.Select(x => new XElement("caption", x)));


This will generate the result like,

XML
<captions>
  <caption>a</caption> 
  <caption>b</caption> 
  <caption>c</caption> 
</captions>


In your scenarion it assumes, there is a single node
XML
<caption></caption>
with a value of
C#
data.ToList().Select(x => x)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900