开发者

XML from DataTable using Linq

This code

XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);

does not work for me, because the node names are derived from the columns' encoded ColumnName property and will look like "last_x20_name", for instance. This I cannot use in the resulting Excel spreadsheet. In order to treat the column names to make them something more friendly, I need to generate the XML myself.

I like LINQ to XML, and one of the responses to this question contained the following snippets:

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

The entire goal is to dynamically derive the column names from the dataset, so hardcoding them is not an option. Can this be done with Linq and without making the code much longer?


It ought to be possible.

In order to use your Dataset as a source you need Linq-to-Dataset.

Then you would need a nested query

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


I appreciate the answers, but I had to abandon this approach altogether. I did manage to produce the XML that I wanted (albeit not with Linq), but of course there is a reason why the default implementation of the XmlDataDocument constructor uses the EncodedColumnName - namely that special characters are not allowed in element names in XML. But since I wanted to use the XML to convert what used to be a simple CSV file to the XML Spreadsheet format using XSLT (customer complains about losing leading 0's in ZIP codes etc when loading the original CSV into Excel), I had to look into ways that preserve the data in Excel.

But the ultimate goal of this is to produce a CSV file for upload to the payroll processor, and they mandate the column names to be something that is not XML-compliant (e.g. "File #"). The data is reviewed by humans before the upload, and they use Excel.

I resorted to hard-coding the column names in the XSLT after all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜