How to use For loop inside XElement

66 views Asked by At

I try to create an XML document from a recieved List<T> which T is the type of the list.

so, the problem is when I try to use a for loop inside XElement I get errors.

My idea is ccreating an XML Document contains elements based on the T properties

So please how can I use the for loop inside the XElement?

1

There are 1 answers

0
Chris Phillips On

As for your error, you cant pass a for-loop as a method parameter. I see what you're getting at here, but you're doing it kind of inverted. Instead of placing the for-loop into the add method, put the add method into the for loop:

for (int i = 0; i < PropertiesLength; i++)
{ 
    var element = new XElement(dataAsList_Properties[i].Name, dataAsList_Properties[i].GetValue(d));
    xdoc.Root.Element(childElementsName).Add(element);
}

Also:

Might I suggest having T implement a certain interface? This will allow you setup methods that are available across all of your types so that your data is more accessible for your conversion to XML