将以下XML导出到Datatable
本文关键字:Datatable XML | 更新日期: 2023-09-27 17:50:45
我在c#中使用HttpWebRequest获得以下XML字符串。
My response XML
<response>
<accounts>
<account>
<city>Some City</city>
<accountId>1234567</accountId>
<companyName>My Company</companyName>
<country>My Country</country>
<email>myemail@yahoo.com</email>
<enabled>1</enabled>
</account>
<account>
<city>Some Other City</city>
<accountId>0987654</accountId>
<companyName>My Other Company</companyName>
<country>My Country</country>
<email>myotheremail@yahoo.com</email>
<enabled>1</enabled>
</account>
</accounts>
<total>2</total>
<limit>20</limit>
<offset>0</offset>
</response>
我需要用以下模式将XML导出到一个数据表。
accountId | companyName | city | country | email | enabled
1234567 | My Company | Some City | My Country | myemail@yahoo.com | 1
0987654 | My Other Company | Some Other City | My Country | myotheremail@yahoo.com | 1
这是我第一次使用XML,我很困惑如何做到这一点。
// Forming a DataTable
dt = new DataTable("Accountdata"); // System.Data.DataTable
dt.Columns.Add("Account ID");
dt.Columns.Add("Company Name");
dt.Columns.Add("City");
dt.Columns.Add("Country");
dt.Columns.Add("Email");
dt.Columns.Add("Enabled");
// XML Part
string path = "accounts.xml";
XmlDocument XMLDoc = new XmlDocument(); // System.Xml.XmlDocument
XMLDoc.Load(path);
foreach (XmlNode AccData in XMLDoc.SelectNodes("/response/accounts/account"))
{
if (AccData["accountId"] == null)
{
continue;
}
else
{
// Fill the DataTable line by line
int AccountId = Convert.ToInt32(AccData["accountId"].InnerText);
string CompanyName = AccData["companyName"].InnerText;
string City = AccData["city"].InnerText;
string Country = AccData["country"].InnerText;
string Email = AccData["email"].InnerText;
int Enabled = Convert.ToInt32(AccData["enabled"].InnerText);
dt.Rows.Add(AccountId, CompanyName, City, Country, Email, Enabled);
}
}
应该正好给你想要的。现在您有了自己的结构,可以进一步处理数据或将其保存到数据库
使用的类在焦点:
- MSDN - XmlDocument类(System.Xml)
- MSDN - DataTable Class (System.Data)