我想在xml中动态添加节点,文件数组包含大号no。的文件所以我想避免写这个语句新的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>
答案 0 :(得分: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))))));