私の問題は、店名が会社名のサブ要素でなければならないということですが、何が起こるかというと、それらが行内で同じであるということです。
出力例は次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<Records>
<CompanyName>Company 1</CompanyName>
<StoreName>Store 2</StoreName>
<StoreName>Store 3</StoreName>
<StoreName>Store 5</StoreName>
<CompanyName>Company 2</CompanyName>
<StoreName>Store 1</StoreName>
<StoreName>Store 4</StoreName>
</Records>
これが私のコードです:
qlCommand cmd = new SqlCommand("select company_name, company_id from company", cn);
//SqlCommand cmd = new SqlCommand("SELECT dbo.company.company_name, dbo.store.store_name, dbo.store.company_id FROM dbo.company INNER JOIN dbo.store ON dbo.company.company_id = dbo.store.company_id", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
SqlCommand cmd2 = new SqlCommand("select store_name, company_id from store", cn);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
adapter2.Fill(dt2);
dataGridView1.DataSource = dt;
XElement xml = new XElement("Records");
foreach (DataRow row in dt.Rows)
{
xml.Add(new XElement("CompanyName", row["company_name"].ToString()));
foreach (DataRow row1 in dt2.Rows)
{
if(row["company_id"].ToString() == row1["company_id"].ToString())
{
xml.Add(new XElement("StoreName", row1["store_name"].ToString()));
}
}
}
xml.Save("C:\\Users\\PHWS13\\Desktop\\test.xml");