XML Writer stored results to string

c#, c#-4.0, linq, linq-to-xml, xml

Solution

Just use overloaded method `XmlWriter.Create(StringBuilder output)` to create xml string. In this case all output will be written to `StringBuilder` instead of file:

StringBuilder builder = new StringBuilder();
XmlWriter writer = XmlWriter.Create(builder);
//... build xml here

string xml = builder.ToString();

Also you can write xml to `MemoryStream` with `XmlWriter.Create(Stream output)`.

Stream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
// ... build xml here

stream.Position = 0;
string xml = new StreamReader(stream).ReadToEnd();

UPDATE

Extension method below will generate your xml string. By default it uses first column as element names, but you can pass any column index for column with meta data. Also I use table name to generate "Employees" tag, so provide name when you create data table `DataTable dt = new DataTable("Employees");`.

public static string ToXml(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();
}

Usage is very simple:

string xml = dt.ToXml();

Output:

<Employees>
  <Product_Name>
    <hello1>product1</hello1>
    <hello2>product2</hello2>
    <hello3>product3</hello3>
    <hello4>product4</hello4>
  </Product_Name>
  <product_Price>
    <hello1>111</hello1>
    <hello2>222</hello2>
    <hello3>333</hello3>
    <hello4>444</hello4>
  </product_Price>
</Employees>

Problem

Possible Duplicate: Alternative ways to convert data table to customized XML ``` DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32"))); fillRows("hello1", dt, "product1", 1111); fillRows("hello2", dt, "product2", 2222); fillRows("hello3", dt, "product3", 3333); fillRows("hello4", dt, "product4", 4444); var xmlColumnZero = dt.AsEnumerable().Select(col => col[0].ToString()).ToArray() ; // row 0 turnovermultiplieer var xmlRowZero = dt.Columns; string firstColumnHeader = dt.Columns[0].ToString(); // XmlDocument xmldoc = new XmlDocument(); XmlWriter writer = XmlWriter.Create("employees.xml"); writer.WriteStartDocument(); writer.WriteStartElement("Employees"); // XmlElement first = xmldoc.CreateElement("Order"); //xmldoc.AppendChild(first); foreach (DataColumn dc in dt.Columns ) { if (dc.ToString() == firstColumnHeader) continue; string firstcol = dc.ToString(); writer.WriteStartElement(firstcol); // XmlElement colRoot = xmldoc.CreateElement(firstcol); //first.AppendChild(colRoot); for (int i = 0 ; i <dt.Rows.Count && i< xmlColumnZero.Length ; i++) { string firstrow = xmlColumnZero[i]; string dtagaga = dt.Rows[i][dc].ToString(); writer.WriteElementString(firstrow, dtagaga); // XmlElement rowRoot = xmldoc.CreateElement(firstrow, dtagaga); //colRoot.AppendChild(rowRoot); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); ``` I want the XMl to be stored into a string while i am creating XMLWriter. Is there another way i can create xml out of the table XML should look like The xml writer method stores everything into an xml file in the program location. Would prefer a string to be saved ``` <Employees> <Product_Name> <hello1>product1</hello1> hello2>product2</hello2> hello3>product3</hello3> hello4>product4</hello4> </product_name> <product_Price> <hello1>1111</hello1> hello2>2222</hello2> hello3>3333</hello3> hello4>4444</hello4> </product_Price> </Employees> ```

Original source