C# XElement.Parse不允许进行循环
我的程序使用XML构建一个html文件。我使用System.Xml,使用System.Xml.Linq。 我希望以这种方式保持代码的形式,但是这个解决方案不起作用,因为XElement.Parse不允许我创建循环。有人能帮忙吗C# XElement.Parse不允许进行循环,c#,sql,xml,xelement,C#,Sql,Xml,Xelement,我的程序使用XML构建一个html文件。我使用System.Xml,使用System.Xml.Linq。 我希望以这种方式保持代码的形式,但是这个解决方案不起作用,因为XElement.Parse不允许我创建循环。有人能帮忙吗 StringBuilder table_dynamic10 = new StringBuilder(); using (SqlConnection conn = new SqlConnection(conString)) { string query = stri
StringBuilder table_dynamic10 = new StringBuilder();
using (SqlConnection conn = new SqlConnection(conString))
{
string query = string.Format("{0}{1}'", "SELECT [VALUE1],[VALUE2] FROM ...");
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
table_dynamic10.Append("<tr><td>" + reader["VALUE1"].ToString() + "</td><td>" + reader["VALUE2"].ToString() + "</td></tr>");
}
}
}
}
var xDocument = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html",
new XElement("head"),
new XElement("body",
XElement.Parse(table_dynamic10.ToString()))))
我建议直接构建XML,而不是构建字符串:
var body = new XElement("body");
using (SqlConnection conn = new SqlConnection(conString))
{
string query = string.Format("{0}{1}'", "SELECT [VALUE1],[VALUE2] FROM ...");
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
body.Add(new XElement("tr",
new XElement("td", reader["VALUE1"]),
new XElement("td", reader["VALUE2"])));
}
}
}
}
var document = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html", new XElement("head"), body));
请注意,这意味着来自数据库的值将被视为值,并带有适当的引号等,而不是被解析为XML。因此,如果数据库中有一个foo&bar值,那么就可以了,并以foo&;bar.请共享您的XML。@Dominique我不能编译,但如果可以,那么:VALUE1 VALUE2