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

时间:2014-03-24 06:59:47

标签: 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>
    </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),
  new XElement("field", new XAttribute("Name", getExcelColumnName), new XAttribute("Value", getCondition))))));
xml.Save(fileLocation);

我改变了这样的代码

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

但是在过滤器标签关闭后它是如何制作字段我怎么能用上面的格式

1 个答案:

答案 0 :(得分:3)

是的,当你真的想在代表xml.Add元素的对象上调用Add时,你正在调用Sheet

我建议您使用:

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

您也可以将所有field元素表达为查询:

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