Search code examples
c#sqlxmlxelement

XElement.Parse don't t allow to make a loop


My program builds an html file using XML. (I using System.Xml, using System.Xml.Linq). I would like to keep the form of the code in this way, but this solution does not work, because XElement.Parse does not let me create a loop. Can anyone help?

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()))))

Solution

  • Rather than building up a string, I'd suggest building up the XML directly:

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

    Note that this means the values from the database will be treated as values, with appropriate quoting etc, rather than being parsed as XML. So if you have a value of foo & bar in the database then that will be fine, and end up in the XML document as foo &amp; bar.