Error creating XML with XmlWriter

1

I need to create an XML, but when I try to create 2 elements of the error, how do I generate 1 XML with two elements? follow my code

class Program
{
    static void Main(string[] args)
    {

        using (XmlWriter writer = XmlWriter.Create("books.xml"))
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("title", "Graphics Programming using GDI+");
            writer.WriteElementString("author", "Mahesh Chand");
            writer.WriteElementString("publisher", "Addison-Wesley");
            writer.WriteElementString("price", "64.95");
            writer.WriteEndElement();

            writer.WriteStartElement("newBook");
            writer.WriteElementString("title", "Graphics Programming using GDI+");
            writer.WriteElementString("author", "Mahesh Chand");
            writer.WriteElementString("publisher", "Addison-Wesley");
            writer.WriteElementString("price", "64.95");
            writer.WriteEndElement();
            writer.Flush();
        }
    }
}

Error code:

  

System.InvalidOperationException: 'Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. '

    
asked by anonymous 20.08.2018 / 21:20

1 answer

3

You need to define the ROOT element - it is the root element of your tree. The first element you should create is just this node.

writer.WriteStartElement("root");

Your complete code:

class Program
{
    static void Main(string[] args)
    {

        using (XmlWriter writer = XmlWriter.Create("books.xml"))
        {
            writer.WriteStartElement("root");

            writer.WriteStartElement("book");
            writer.WriteElementString("title", "Graphics Programming using GDI+");
            writer.WriteElementString("author", "Mahesh Chand");
            writer.WriteElementString("publisher", "Addison-Wesley");
            writer.WriteElementString("price", "64.95");
            writer.WriteEndElement();

            writer.WriteStartElement("newBook");
            writer.WriteElementString("title", "Graphics Programming using GDI+");
            writer.WriteElementString("author", "Mahesh Chand");
            writer.WriteElementString("publisher", "Addison-Wesley");
            writer.WriteElementString("price", "64.95");
            writer.WriteEndElement();
            writer.Flush();
        }
    }
}
    
20.08.2018 / 22:08