6

I tried to save some elements from my application in xml file but when I started to develop it using this code :

public static void WriteInFile(string savefilepath)
        {
            XmlWriter writer = XmlWriter.Create(savefilepath);
            WriteXMLFile(writer);

        }
private static void WriteXMLFile(XmlWriter writer) //Write and Create XML profile for specific type 
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("cmap");
            writer.WriteAttributeString("xmlns", "dcterms",null, "http://purl.org/dc/terms/");
            writer.WriteElementString("xmlns", "http://cmap.ihmc.us/xml/cmap/");
           // writer.WriteAttributeString("xmlns","dc",null, "http://purl.org/dc/elements/1.1/");
            //writer.WriteAttributeString("xmlns", "vcard", null, "http://www.w3.org/2001/vcard-rdf/3.0#");
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }

I found that the output in notepad are in one line like this :

<?xml version="1.0" encoding="utf-8"?><cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns></cmap>

I want it appear as multiline like this:

<?xml version="1.0" encoding="utf-8"?> <cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns>
</cmap>
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
kartal
  • 17,436
  • 34
  • 100
  • 145
  • The output you want is exactly the same. Try loading it up in XMLEditor and/or Visual Studio. Notepad isn't known for its formatting options. – Security Hound Dec 15 '11 at 14:28

3 Answers3

14

You have create an instance of XmlWriterSettings.

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(savefilepath, settings);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 6
    It's worth mentioning, for any future readers with this issue, that writing a whitespace will stop the new line/indent from working. MSDN for [XmlWriterSettings.Indent](http://msdn.microsoft.com/en-GB/library/system.xml.xmlwritersettings.indent.aspx) - "The elements are indented as long as the element does not contain mixed content. Once the WriteString or WriteWhitespace method is called to write out a mixed element content, the XmlWriter stops indenting. The indenting resumes once the mixed content element is closed." – Kobunite May 02 '13 at 13:44
4
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlWriter.Create(savefilepath, settings))
{
     WriteXMLFile(writer);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

You should use an XmlWriterSettings - set your appropriate formatting options and pass it when creating the XmlWriter.

Read more about it here: http://msdn.microsoft.com/en-us/library/kbef2xz3.aspx

zmbq
  • 38,013
  • 14
  • 101
  • 171