0

我想在 xml 中动态添加节点,文件数组包含大号。的文件,所以我想避免写这个语句new XElement("FileName",files[0])。有没有办法在这个语句上运行 for/foreach 循环或任何其他方式来实现这个目标。

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])))));

输出:

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

1 回答 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))))));
于 2013-10-23T09:50:51.837 回答