I want my XML file to look like this:

<?xml version="1.0"?>

<Student>
  <Name>Jax</Name>
  <Prenume>Teller</Prenume>
</Student>

I wrote the following code in C#:

using System;
using System.Xml;
namespace ReadingXML2
{
    class Class1
    {
        static void Main(string[] args)
        {
            XmlTextWriter textWriter = new XmlTextWriter(@"c:\users\danuts\documents\visual studio 2010\Projects\BD - XML\BD - XML\XMLFile1.xml", null);

            textWriter.WriteStartDocument();

                textWriter.WriteString("\n");
                textWriter.WriteStartElement("Student");
                textWriter.WriteString("\n");
                textWriter.WriteElementString("Name","Jax");
                textWriter.WriteString("\n");
                textWriter.WriteElementString("Prenume","Teller");

                textWriter.WriteEndElement();

            textWriter.WriteEndDocument();
            textWriter.Close();
        }
    }
}

It breaks at line "textWriter.WriteString("\n");" and I can't figure out why. The error I get is this:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

Additional information: Token Content in state Prolog would result in an invalid XML document.

Recommended Answers

All 2 Replies

Why are you adding the newlines anyway? Just for readability?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.