Link to home
Start Free TrialLog in
Avatar of MangoMarcus
MangoMarcus

asked on

Line Breaks in XML Files

How do I get a line break or carriage retunr in the actual XML file so it does not go across one line. I have tried the XMLWriterSettings but it does not appear to work. The code is as below:

ublic partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        // location to the XML file to write
        String strFilePath = "c:\\Projects\\company\\App_Data\\movies.xml";

        // create an instance of the XmlTextWriter object
        XmlTextWriter objWriter = new XmlTextWriter(strFilePath, System.Text.Encoding.UTF8);

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        settings.NewLineOnAttributes = true;

        objWriter.WriteStartElement("order");
        objWriter.WriteAttributeString("orderID", "367A54");
        objWriter.WriteAttributeString("date", "2001-05-03");
        objWriter.WriteElementString("price", "19.95");
        objWriter.WriteEndElement();

        objWriter.Flush();

        // clear up memory
         objWriter.Close();

         // successfully done
         result.Text = "XML file ";
         
    }
}
ASKER CERTIFIED SOLUTION
Avatar of Ashley Bryant
Ashley Bryant
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dmitry G
I think the problem is that you haven't set your xmlWriterSettings...

You need to create settings before creating a writer and pass this settings object to a writer constructor,

something like


        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        settings.NewLineOnAttributes = true;


XmlTextWriter writer   = XmlTextWriter.Create("books.xml", settings);
Avatar of MangoMarcus
MangoMarcus

ASKER

Cheers Ashley, worked a treat!

(Thanks Anarki - its seems to throw an error when you swap (strFilePath, System.Text.Encoding.UTF8) for (strFilePath, System.settings) - obviously something im doing wrong!)
Sorry Anarki, I meant (strFilePath, settings)