简体   繁体   中英

c# write XML looping a datatable or dataset

I need to create a XML files from a dataset or datable; foreach record in dataset I have to create one file, following my code:

SqlDataAdapter da = new SqlDataAdapter("select top 5 * from dbo.Log", con);
DataSet ds = new DataSet();
da.Fill(ds, "Log");
DataTable dt = new DataTable("Log");
da.Fill(dt);                
foreach (DataRow row in dt.Rows)
{
row.Table.WriteXml("D:\\" + row["id"] + ".xml");
// some other code...

That create 5 XML files but inside there are all 5 records found in the dataset/datatable... I want only one record for every file! How can I do so? thanks

You're using row.Table.WriteXml(...) . This writes the entire table, so: all rows. As far as I know, there is no inbuilt API for exporting a single row at a time; I guess you could clone/add/remove the row into an identical but empty table?

Something like (untested):

var clone = dt.Clone(); // is empty
foreach(DataRow row in dt.Rows)
{
    clone.Rows.Clear();
    clone.ImportRow(row);
    clone.WriteXml("D:\\" + row["id"] + ".xml");
}

It might be easier to use XmlWriter , though.

Use XmlTextWriter. Below is just an example. You can modify it as per your need.

XmlTextWriter writer = new XmlTextWriter("D:\\" + row["id"] + ".xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("Table");
createNode("1", "Product 1", "1000", writer);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM