Search code examples
c#xmlxmlwriter

XmlWriter writing everything to a single line


I am writing an XML file, however when I go to read it it is all on the same line.

Can someone please look at my code and let know why its all appearing on the same line rather than in the correct format.

The code as you should see is writing a few nodes, then it is writing the code, name, formula, and so on... It's also checking that the formula from datarow 8 and beyond are not duplicates

var exportFile = "c:\\temp\\export.xml";
XmlWriter xmlWriter = XmlWriter.Create(exportFile);

xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("designExport");
xmlWriter.WriteStartElement("designs");
xmlWriter.WriteStartElement("design");
foreach (DataRow dr in xltbl.Rows)
{
    xmlWriter.WriteStartElement("code");
    xmlWriter.WriteString(dr[0].ToString());
    xmlWriter.WriteEndElement();
    xmlWriter.WriteStartElement("name");
    xmlWriter.WriteString(dr[1].ToString());
    xmlWriter.WriteEndElement();
    for (var i = 2; i < xltbl.Columns.Count; i++)
    {
        if (i >= 8 && dr[i] != dr[i - 8])
        {
            if (string.IsNullOrEmpty(dr[i].ToString())) continue;
            xmlWriter.WriteStartElement("forumula");
            xmlWriter.WriteString(dr[i].ToString());
            xmlWriter.WriteEndElement();
            xmlWriter.WriteStartElement("coverage");
            xmlWriter.WriteString("0");
            xmlWriter.WriteEndElement();
            xmlWriter.WriteStartElement("usageFactor");
            xmlWriter.WriteString("0");
            xmlWriter.WriteEndElement();
        }
    }
}
xmlWriter.WriteEndDocument();
xmlWriter.Close();

Solution

  • The documentation of the XmlWriter.Create(string) method says that:

    An XmlWriterSettings object with default settings is used to create the writer. If you wish to specify the features to support on the created writer, use the overload that takes an XmlWriterSettings object as one of its arguments, and pass in a XmlWriterSettings object with the correct settings.

    Apparently, the default settings is not what you want.

    You must define the desired writer behaviour using the XmlWriterSettings class:

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    // other settings...
    
    XmlWriter xmlWriter = XmlWriter.Create(exportFile, settings);
    

    There are quite a lot of properties you can define to adjust the generated output. Have a quick look at the documentation.