2013-10-23 96 views
0

我想在xml中動態添加節點,文件數組包含大號。的文件,所以我想避免寫這個聲明新的XElement(「文件名」,文件[0])。有沒有辦法在這個語句或任何其他方式上運行for/foreach循環來實現這個目標。使用linq動態添加節點在xml中使用linq

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