使用linq在xml中动态添加节点
我想在xml中动态添加节点,文件数组包含大量文件,因此我想避免编写此语句new-XElement(“FileName”,files[0])。有没有一种方法可以在此语句上运行for/foreach循环,或者有没有其他方法可以实现此目标使用linq在xml中动态添加节点,xml,linq,linq-to-xml,Xml,Linq,Linq To Xml,我想在xml中动态添加节点,文件数组包含大量文件,因此我想避免编写此语句new-XElement(“FileName”,files[0])。有没有一种方法可以在此语句上运行for/foreach循环,或者有没有其他方法可以实现此目标 string [] sep = { ",",";" }; string[] files = txtFiles.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries); XDocument xdoc = new
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>
文件1
文件2
文件3
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))))));