0

I have a very strange null reference exception and it's blocking my progress.

I'm working on making a book. Each book has pages and each page can have text items and an image on them. I'm trying to save these objects in a Xml file. The first time I save the objects all goes well. The Xml is created, loaded, filled by c# and saved. When I try to add/save a new page to the book I'm unable to get the Xml file that already exists. The problem is that my code never reaches the point where I can read a file. It errors when I'm creating an empty XDocument object. The error says "documentType is a null reference".

The first time the create method is called is when I save the first set of objects of the first page. I don't get any errors and the Xml is correctly saved. But when I try to save again (either a new page or the current one) I get the error (Image bottom of post).

Debugger stops after XDocument doc; (in LoadXml) it then throws the NullReferenceException as displayed in the image. Solved by adding a XDocumentType node to the XML.

New Error: The new error says that the Root of the XDocument is a null reference. Before it was the DocumentType giving the error.

Load Xml

/// <summary>
/// Loads the XML file for the given path.
/// A new document will be created if the file does not exist or is corrupted.
/// </summary>
/// <param name="collectionId">The collectionId to load the file from.</param>
/// <param name="newFile">A boolean result which states if the returned file is new.</param>
/// <returns>The requested file or a new one.</returns>
public static XDocument LoadXml(int collectionId, int version, out bool newFile, CollectionType collectionType)
{
    newFile = false;
    XDocument doc; // Here I get the error when I run the code for a second time

    string file = GetXmlPath(collectionId, collectionType, version) + "/photobook.xml";

    if (System.IO.File.Exists(file))
    {
        try
        {
            doc = XDocument.Load(file);
        }
        catch
        {
            newFile = true;
            doc = CreateNewXml();
        }
    }
    else
    {
        newFile = true;
        doc = CreateNewXml();
    }

    return doc;
}

SaveNewPage

/// <summary>
/// Add and save a new page to an existing book. 
/// </summary>
/// <param name="pageInfoParam">New pageInfo object that has to be added to the collection.</param>
/// <param name="collectionId">Id of the collection which is being edited.</param>
/// <param name="version">Version of the collection which is being edited.</param>
/// <returns>True if succesful.</returns>
public static bool SaveNewPageInfo(PageInfo pageInfoParam, int collectionId, int version)
{

    bool result = false;
    // Make sure the collection exists
    if (!CollectionExists(collectionId, version))
    {
        Logger.log("Error: Collection {0} not found.", collectionId);
        throw new Exception("Fotoboek niet gevonden.");
    }

    Logger.log("Saving page info...");

    bool newFile;
    XDocument doc = XmlService.LoadXml(collectionId, version, out newFile, CollectionType.collection);

    if (!newFile)
    {
        // This should never happen, we just successfully saved the XML
        result = false;
        Logger.log("Xml could not be loaded when trying to save a new page.");
        throw new Exception("Fout bij het opslaan van de nieuwe pagina.");
    }

    // Get all current pages from the document.
    List<XElement> pages = doc.Root.Element("inner").Elements("page").ToList();

    #region New page in new book
    // If no pages available we have to add a new page element.

    #endregion

    #region Edit existing page in book
    // If pages exist find the page we edited, remove all text and add the new text.

    #endregion

    // Try to save the XML file
    if (!XmlService.SaveXml(doc, collectionId, version))
    {
        Logger.log("Xml could not be saved.");
        throw new Exception("De pagina kon niet worden opgeslagen.");
    }
    else
    {
        Logger.log("Page info for collection {0} saved successfully in Xml.", collectionId);
        result = true;
        return result;
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Book SYSTEM "Book.dtd"> 
<album version="0.2" settingsVersion="1">   
    <size />   
    <cover />   
    <inner>
       <page>
           <pagenumber>1</pagenumber>
           <image>04.jpg</image>
           <textelements>
             <text>
               <value>Test </value>
               <font>arial</font>
               <size>18pt</size>
               <style>normal</style>
               <weight>normal</weight>
               <color>#77DD44</color>
               <rotation>0</rotation>
               <alignment>start</alignment>
               <position>
                   <x>50</x>
                   <y>50</y>
               </position>
             </text>
          </textelements>
        </page> 
    </inner> 
 </album>

Error Message in Visual Studio

Da Bazz
  • 51
  • 1
  • 10
  • You are receiving the error on the return doc; Debug and see what is going on. – mybirthname Nov 01 '16 at 11:00
  • Provide a [mcve] that demonstrates the problem. Any attempt to work out why it fails would pretty much be a guess. – Charles Mager Nov 01 '16 at 11:08
  • The debug jumps from `XDocument doc;` to `return doc`. Because of the NullReferenceException in the XDocument object. The NullReferenceException is inside the XDocument object and as far as I know I have no control over the documentType property of XDocument. – Da Bazz Nov 01 '16 at 11:17
  • My guess is that there is a problem with your xml file and may be missing a root element. Maybe add a dtd node to your xml. Something like ..... – Haim Katz Nov 01 '16 at 12:06
  • @HaimKatz I added a doctype to the xml and I now get a different null reference exception. The c# object says that now Root, not DocumentType is null. I added an example of how the Xml file looks now. – Da Bazz Nov 01 '16 at 13:46
  • Maybe it doesn't like the fake dtd. In VS open the xml file. Click on the XML menu item and select create schema. Save that file as book.xsd.. – Haim Katz Nov 07 '16 at 13:16
  • The Root being null didn't matter as the Nodes were still available. It might not be clean but I'm able to load/save the Xml and that's all that really matters. – Da Bazz Nov 09 '16 at 09:26

0 Answers0