0

I am trying to create a dynamic xelement.

I want the output in Xelement as :

<text> text1 </text>
<text> text2 </text>

So, I wrote code as :

        string[] arr = new string[2];
        arr[0] = "text1";
        arr[1] = "text2";

        XElement xElement1;
        XElement xElement12 = new XElement(string.Empty);
        for (int i=0;i<arr.Length;i++)
        {
            xElement1 = new XElement("text");
            xElement1.Add(arr[i].ToString());
            xElement12.Add(xElement1);
        }

But, with this code, I get output as :

<text>
    <text> text1 </text>
    <text> text2 </text>
</text>

Can anyone please let me know.I want this data in Xelement and there can be n number of data in the array.

demo stack
  • 103
  • 1
  • 1
  • 7
  • 2
    A single `XElement` maps to one single XML element. Looks like you want a `List`. Also, be aware that a valid XML document has [only one root element](https://en.wikipedia.org/wiki/Root_element). – dbc Feb 18 '16 at 00:36

1 Answers1

0

Doing it like this is cleaner and easier to read. The strings can be replaced dynamically

            XElement root = new XElement("root", new XElement[] {
                new XElement("text", "text1"),
                new XElement("text", "text2")
            });
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • I do not know how many array elements I would be getting. I am making that dynamic. So I cant know that whether i have text1, text2 or text3 or all . – demo stack Feb 18 '16 at 15:07
  • Your solution you are calling the XElement constructor and then adding the tagname and value. it can be done in one step like in my code. – jdweng Feb 18 '16 at 22:41