Waqar Janjua
Waqar Janjua

Reputation: 6123

dynamically add nodes in xml using linq

I want to dynamically add nodes in xml, files array contains large no. of files so I want to avoid writing this statement new XElement("FileName",files[0]) . Is there a way to run a for/foreach loop on this statement or any other way to achieve this goal.

string [] sep = { ",",";" };
string[] files = txtFiles.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);

XDocument xdoc = new XDocument(
                    new XDeclaration("1.0", "utf-16", "true"),
                    new XElement("data",
                        new XElement("rn",
                            new XAttribute("Active", "true"),
                            new XAttribute("Name", txtReportName.Text),   
                        new XElement("Files",
                            new XElement("FileName",files[0]),
                            new XElement("FileName",files[1]),
                            new XElement("FileName",files[2])))));

Output:

<data>
<rn Active="true" Name="testdata">
<Files>
  <FileName>file1</FileName>
  <FileName>file2</FileName>
  <FileName>file3</FileName>
</Files>
</rn>
</data>

Upvotes: 0

Views: 68

Answers (1)

Fung
Fung

Reputation: 3558

string [] sep = { ",",";" };
string[] files = txtFiles.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);

XDocument xdoc = new XDocument(
                    new XDeclaration("1.0", "utf-16", "true"),
                    new XElement("data",
                        new XElement("rn",
                            new XAttribute("Active", "true"),
                            new XAttribute("Name", txtReportName.Text),   
                        new XElement("Files",
                            files.Select(x => new XElement("FileName", x))))));

Upvotes: 1

Related Questions