C# DataSet To Xml, Node Rename
DataSet ds = GetExcelToXml("test.xls");
string filename = @"C:\test.xml";
FileStream myFileStream = new FileStream(filename, FileMode.Create);
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.开发者_JS百科Default);
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();
Output Xml
<NewDataSet>
<Table>
<UserName>bla1</User_Name>
<Mail>bla1@bla2.com</Mail>
<Address>World</Address>
</Table>
</NewDataSet>
I need Xml Node Name
<ROWS>
<ROW>
<UserName>bla1</User_Name>
<Mail>bla1@bla2.com</Mail>
<Address>World</Address>
</ROW>
</ROWS>
How To Make ?
Try this,
ds.DataSetName = "ROWS";
ds.Tables[0].TableName = "ROW";
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();
XmlDocument myXml;
myXml.Load(myXmlWriter); //Not sure if this will work, but you get the idea
myXml.InnerXml = myXml.InnerXml.Replace("< NewDataSet", "< ROWS")
.Replace("< /NewDataSet>", "< /ROWS>")
.Replace("< Table", "< ROW")
.Replace("< /Table>", "< /ROW>");
Here is a sample C# application which will read the input XML and then copy different XML/Data tables to other files using the Table name:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataSet dsXml = new DataSet();
dsXml.ReadXml("mydata.xml");
for (int i = 0; i < dsXml.Tables.Count; i++)
{
Console.WriteLine("Table Name: " + dsXml.Tables[i].TableName);
DataSet newDataSet = new DataSet();
newDataSet.Tables.Add(dsXml.Tables[i].Copy());
FileStream myFileStream = new FileStream(dsXml.Tables[i].TableName + ".xml", FileMode.Create);
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Default);
newDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}
}
}
}
In case anyone comes here looking for the opposite direction problem where a typed dataset table name has changed since the xml files were written.
// for xml files created prior to rename of Sample table to SampleS,
// rename the Sample table, read xml,
// then rename table back to current SampleS
if (ds.SampleS.Count == 0)
{
ds = new AnalysisDSX();
ds.Tables["SampleS"].TableName = "Sample";
ds.ReadXml(xmlFilePath);
ds.Tables["Sample"].TableName = "SampleS";
}
精彩评论