Hi @John , Welcome to Microsoft Q&A,
In fact, we usually use xml serialization directly to dataset for use.
You can use Dataset.ReadXml().
<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder OrderDate="1900-01-01" >
<ShipTo country="US">
<name>name1</name>
<street>street1</street>
<city>city1</city>
<state>state1</state>
<zip>1</zip>
</ShipTo>
<ShipTo country="US">
<name>name2</name>
<street>street2</street>
<city>city2</city>
<state>state2</state>
<zip>-79228162514264337593543950335</zip>
</ShipTo>
<BillTo country="US">
<name>name1</name>
<street>street1</street>
<city>city1</city>
<state>state1</state>
<zip>1</zip>
</BillTo>
</PurchaseOrder>
private void Form1_Load(object sender, EventArgs e)
{
// 1. Create a new DataSet
DataSet dataSet = new DataSet();
try
{
// 2. Load data from XML file to DataSet
dataSet.ReadXml("XMLFile1.xml");
// 3. Bind DataSet to DataGridView
dataGridView1.DataSource = dataSet.Tables[1];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message);
}
}
Or you can manually serialize the target xml according to your needs:
private void Form1_Load(object sender, EventArgs e)
{
try
{
//Create a new DataSet
DataSet dataSet = new DataSet();
//Create a DataTable to save data
DataTable dataTable = new DataTable("ShipToData");
//Add required columns
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Street", typeof(string));
dataTable.Columns.Add("State", typeof(string));
//Create an XmlDocument object and load the XML file
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile1.xml"); // Please replace with the actual XML file path
// Use XPath expression to get ShipTo element
XmlNodeList? shipToNodes = xmlDoc.SelectNodes("/PurchaseOrder/ShipTo");
foreach (XmlNode? shipToNode in shipToNodes)
{
string name = shipToNode.SelectSingleNode("name").InnerText;
string street = shipToNode.SelectSingleNode("street").InnerText;
string state = shipToNode.SelectSingleNode("state").InnerText;
//Add data rows to DataTable
dataTable.Rows.Add(name, street, state);
}
//Add DataTable to DataSet
dataSet.Tables.Add(dataTable);
dataGridView1.DataSource = dataSet.Tables["ShipToData"];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.