C# 如何将具有多个属性的元素添加到特定节点

C# 如何将具有多个属性的元素添加到特定节点,c#,asp.net,xml,C#,Asp.net,Xml,这是我的XML文档 <Filters> <Filter Name="ddd"> <File Name="filename.xls" Location="\\path\filename.xls"> <Sheet Name="'sheetname'"> <field Name="Pick up point" Condition="LIKE" Value="k" /> </Sheet&

这是我的XML文档

<Filters>
  <Filter Name="ddd">
    <File Name="filename.xls" Location="\\path\filename.xls">
      <Sheet Name="'sheetname'">
        <field Name="Pick up point" Condition="LIKE" Value="k" />
      </Sheet>
    </File>
  </Filter>
  <Filter Name=""ccc>
    <File Name="filename.xls" Location="\\path\filename.xls">
      <Sheet Name="'sheetname'">
        <field Name="Pick up point" Condition="LIKE" Value="k" />
      </Sheet>
   </File>
 </Filter>
<Filters>
我像这样修改了代码

xml.Add(new XElement("Filter", new XAttribute("Name", getCriteriaName),
     new XElement("File", new XAttribute("Name", getFileName), new XAttribute("Location", excelFileLocation),
     new XElement("Sheet", new XAttribute("Name", getExcelSheetName))));
while (conditions.Rows.Count > rowCount)
{

    xml.Add(new XElement("field", new XAttribute("Name", conditions.Rows[rowCount][0]),new XAttribute("Condition", conditions.Rows[rowCount][1]), new XAttribute("Value", conditions.Rows[rowCount][2])));

    isSaved = true;
    rowCount++;
}
xml.Save(fileLocation);

但是在过滤器标记关闭后,它会生成字段。我怎样才能以上述格式执行它呢?

是的,您正在调用
xml.Add
,而实际上您需要调用
Add
来表示
工作表
元素的对象

我建议您使用:

XElement sheet = new XElement("Sheet", new XAttribute("Name", getExcelSheetName);
while (conditions.Rows.Count > rowCount)
{
    sheet.Add(new XElement("field", ...));
    isSaved = true; // Unclear what this is for...
    rowCount++;
}
xml.Add(new XElement("Filter", new XAttribute("Name", getCriteriaName),
             new XElement("File", ...),
             sheet);
您还可以将所有这些
字段
元素表示为查询:

XElement sheet = new XElement("Sheet", new XAttribute("Name", getExcelSheetName),
    conditions.Rows.Select(row => ...));
XElement sheet = new XElement("Sheet", new XAttribute("Name", getExcelSheetName),
    conditions.Rows.Select(row => ...));