Search code examples
c#xmlwindows-phone-7record

Data at the root level is invalid. Line 1, position 1, when writing


This is my code for adding data to xml:

IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("People.xml", System.IO.FileMode.Open, isstore);

XDocument xmldetails = XDocument.Load(bookfile);
XElement books =
    new XElement("person",
    new XAttribute("id", "5"),
    new XAttribute("name", "Book Title"),
    new XAttribute("beneficiary", "Book Author"),
    new XAttribute("description", "Book Author"),
    new XAttribute("deadline", "Book Author"),
    new XAttribute("price", "Fiction"));
xmldetails.Root.Add(books);

xmldetails.Save(bookfile);
bookfile.Close();

This is People.xml:

<?xml version="1.0" encoding="utf-8" ?>
<people>
    <person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
</people>

When I click button I have this error:

Data at the root level is invalid. Line 1, position 1.


Solution

  • It appears that your XML file might be missing a root node, and you are trying to add the child node to a non-existent parent. Make sure that your source XML is well-formed.

    What you should do, by the way, in your code, is this:

    XElement books =
                new XElement("person",
                new XAttribute("id", "5"),
                new XAttribute("name", "Book Title"),
                new XAttribute("beneficiary", "Book Author"),
                new XAttribute("description", "Book Author"),
                new XAttribute("deadline", "Book Author"),
                new XAttribute("price", "Fiction"));
    xmldetails.Element("People").Add(books);