简体   繁体   English

在C#中使用linq to xml以正确的方式创建xml的子元素

[英]Creating a subelement of xml the right way using linq to xml in C#

My problem is that the store name should be the sub element of company name but what happen is that they are the same in line How can I fix this? 我的问题是商店名称应该是公司名称的子元素,但是发生的事情是它们在行中是相同的。如何解决此问题?

Here is the sample output: 这是示例输出:

    <?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>

Here is my code: 这是我的代码:

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");

The problem is that you are adding the element to xml which is always at the same level (ie you are always adding elements as children of your "Records" element). 问题在于您正在将元素添加到始终处于同一级别的xml中(即,您始终将元素添加为“ Records”元素的子元素)。

Try this: 尝试这个:

XElement xml = new XElement("Records");
foreach (DataRow row in dt.Rows)
{
    var companyName = new XElement("CompanyName", row["company_name"].ToString())
    xml.Add(companyName);
    foreach (DataRow row1 in dt2.Rows)
    {
        if(row["company_id"].ToString() == row1["company_id"].ToString())
        {
            companyName.Add(new XElement("StoreName", row1["store_name"].ToString()));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM