This is default behavior of WriteXml() method when we create xml then it adds <NewDataSet> node as root xml node and <Table> as child node. In this article, I am explaining- How to change <NewDataSet> xml root name while creating xml using WriteXml() method of Dataset?
Let first see the default case-
Suppose you we have one DataSet object ds and we are filling it will data source, like this-
Dataset ds= new DataSet();
ds= datasource;
After that we are using WriteXml() method to create XML, like this-
ds.WriteXml("FileName");
Then in this case output will be like this-
<NewDataSet>
<Table>
<Emp_ID>717</Emp_ID>
<Emp_Name>Jitendra Faye</Emp_Name>
<Salary>35000</Salary>
</Table>
----------
----------
----------
</NewDataSet>
Here we can see that <NewDataSet> and <Table> is default tag here.
Now to change these default tag follow this code, Here I am changing <NewDataSet> tag as <EmployeeRecords> tag and <Table> tag as <Employee> tag.
Here is code-
Dataset ds= new DataSet();
ds= datasource;
//Giving Name to DataSet, which will be displayed as root tag
ds.DataSetName="EmployeeRecords";
//Giving Name to DataTable, which will be displayed as child tag
ds.Tables[0].TableName = "Employee";
//Creating XML file
ds.WriteXml("FilePath");
Now after executing this above code generated XML file will be like this-
<EmployeeRecords>
<Employee>
<Emp_ID>717</Emp_ID>
<Emp_Name>Jitendra Faye</Emp_Name>
<Salary>35000</Salary>
</Employee>
----------
----------
----------
</EmployeeRecords>
Here we can see that DataSet name is coming as root tag and DataTable name is coming as child tag.
Note-
Before giving name to DataTable (ds.Tables[0].TableName) first check that it should not be null otherwise it will cause an error.
Thanks
Thanks for the post. It helped :)
ReplyDelete