代码之家  ›  专栏  ›  技术社区  ›  cdonner

使用LINQ从数据表获取XML

  •  0
  • cdonner  · 技术社区  · 14 年前

    本代码

    XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);
    

    对我来说不起作用,因为节点名是从列的encoded columnname属性派生的,例如看起来像“last_x20_name”。我无法在生成的Excel电子表格中使用此功能。为了处理列名以使它们更友好,我需要自己生成XML。

    我喜欢linq-to-xml,以及对 this question 包含以下代码段:

    XDocument doc = new XDocument(new XDeclaration("1.0","UTF-8","yes"), 
    new XElement("products", from p in collection 
     select new XElement("product", 
         new XAttribute("guid", p.ProductId),  
         new XAttribute("title", p.Title), 
         new XAttribute("version", p.Version)))); 
    

    整个目标是从数据集中动态地派生列名,因此硬编码它们不是一个选项。这可以用LINQ来完成吗,而不需要让代码长得多?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Henk Holterman    14 年前

    这应该是可能的。

    为了将数据集用作所需的源 Linq-to-Dataset .

    然后需要一个嵌套查询

    // untested
    var data = new XElement("products", 
       from row in ds.Table["ProductsTable"].Rows.AsEnumerable()
       select new XElement("product", 
         from column in ds.Table["ProductsTable"].Columns  // not sure about this
         select new XElement(colum.Fieldname, rows[colum.Fieldname]) 
       ) );
    
        2
  •  1
  •   cdonner    14 年前

    我很感激这些答案,但我不得不完全放弃这种方法。我确实设法生成了我想要的XML(尽管没有使用Linq),但当然,有一个原因,就是XMLDataDocument构造函数的默认实现使用了 编码列名称 -也就是说,XML中的元素名称中不允许使用特殊字符。但是,由于我想使用XML将以前简单的csv文件转换为使用xslt的xml电子表格格式(客户抱怨在将原始csv加载到Excel时丢失了邮政编码中的前导0),所以我不得不寻找在Excel中保存数据的方法。

    但这项工作的最终目标是生成一个csv文件,以便上传到工资单处理程序,并且他们要求列名必须是不符合XML的(例如“文件”)。数据在上传前由人进行审查,并使用Excel。

    毕竟,我在XSLT中对列名进行了硬编码。