将以下XML导出到Datatable

时间:2013-01-06 02:47:59

标签: c# xml datatable httpwebrequest

我在c#中使用HttpWebRequest获取以下XML字符串。

我的回复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,我很困惑如何做到这一点。请帮帮我。

1 个答案:

答案 0 :(得分:1)

// 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);
    }
}               

应该为你提供你想要的东西。 现在您拥有了自己的结构,可以进一步处理数据或将数据保存到数据库

使用了焦点类: