【发布时间】:2016-10-05 20:46:40
【问题描述】:
我有以下数据表:
A B C
----------
A1 B1 C1
A1 B1 C2
A1 B1 C3
A1 B2 C1
A1 B2 C2
----------
我尝试使用 C# 将其转换为 XML 格式,如下所示:
<Data>
<A>
<lable>A1</lable>
<B>
<lable>B1</lable>
<C>
<lable>C1</lable>
<lable>C2</lable>
<lable>C3</lable>
</C>
<lable>B2</lable>
<C>
<lable>C1</lable>
<lable>C2</lable>
</C>
</B>
</A>
</Data>
我进行了深入搜索,并在网上找到了一些有用的东西,例如 this。 但是那个使用关系,我的数据只是一张表。 我也试过这个 C# 代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Data.SqlClient;
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Files;Data Source=localhost");
con.Open();
SqlCommand cmd = new SqlCommand("select * from MyTable",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable("Data");
da.Fill(DT);
dataGridView1.DataSource = DT;
con.Close();
string XML = ToXmlFormat(DT, 0);
Console.WriteLine(XML);
public string ToXmlFormat(this DataTable table, int metaIndex = 0)
{
XDocument xdoc = new XDocument(
new XElement(table.TableName,
from column in table.Columns.Cast<DataColumn>()
where column != table.Columns[metaIndex]
select new XElement(column.ColumnName,
from row in table.AsEnumerable()
select new XElement(row.Field<string>(metaIndex), row[column])
)
)
);
return xdoc.ToString();
}
结果是另一种格式,它不是我解释的嵌套 XML。 see image
如何将表格转换为所需的 XML 格式?
【问题讨论】:
-
数据表,writeXML 会以读取它需要的格式写出来
-
不,我也试过了,它只返回一个节点,你可以试试,但是错了
标签: c# xml nested-table