0

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>

1 Answer 1

1
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))))));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.