0

我正在尝试创建一个简单的笔记应用程序供我自己使用。这个想法是学习 C#/Mono XML 编辑。

我找不到编译器抱怨的 NullReference。不知道为什么。我看不到它。经过几天的搜索,我放弃了......帮助。:)

这是产生错误的代码。该应用程序运行良好,直到我按下按钮添加新笔记。它只是崩溃。add_activated 函数在按下按钮时运行,它应该使用 AddNote 函数。

代码不完整,肯定有一些逻辑错误。但我可以处理这些。我只是想知道为什么它不会运行。

MainActivity.cs:

// (...)
protected void add_activated (object sender, System.EventArgs e)
    {
        Gtk.TextBuffer buffer;          
        buffer = textview1.Buffer;

        Note note = new Note(entry3.Text, buffer.Text);     

        AddNote (note);
    }


    public static void AddNote (Note note)
    {
        string xmlFile = "/home/tomasz/.keeper/keeper.xml";

        XmlDocument xmlDoc = new XmlDocument ();
        xmlDoc.Load (xmlFile);
        XmlNode xmlRoot = xmlDoc.CreateElement("keeper");

        if (!xmlDoc.DocumentElement.Name.Equals("keeper") )
        {       
            xmlDoc.AppendChild (xmlRoot);
        }

        XmlNode xmlNote = xmlDoc.CreateElement ("note");
        XmlNode xmlTitle = xmlDoc.CreateElement ("title");
        XmlNode xmlText = xmlDoc.CreateElement ("text");

        xmlRoot.InsertAfter (xmlRoot.LastChild, xmlNote);
        xmlTitle.InnerText = note.Title;
        xmlNote.InsertAfter (xmlNote.LastChild, xmlTitle);
        xmlText.InnerText = note.Text;
        xmlNote.InsertAfter (xmlNote.LastChild, xmlText);

        xmlDoc.Save (xmlFile);
    }


    protected void remove_activated (object sender, System.EventArgs e)
    {
        throw new System.NotImplementedException ();
    }
    }
}

注意.cs:

using System;

namespace Keeper
{
public class Note
{   
    private string title;
    private string text;

    public string Title {
        get 
        {
            return this.title;
        }
        set 
        {
            this.title = value;
        }
    }
    public string Text
    {
        get 
        {
            return this.text;
        }
        set 
        {
            this.text = value;
        }
    }

    public Note (string title, string text)
    {
        this.Title = title;
        this.Text = text;
    }
}
}
4

1 回答 1

0

直接的问题是你把论据InserAfter弄混了。第一个应该是要插入的节点,第二个应该是参考节点。根元素还没有子元素,因此LastChild将是null,因此是例外。null用作参考点是有效的,但不能用作要添加的节点。

还有其他问题,但你说你能够解决这些问题,所以你去。

于 2013-08-29T12:49:13.160 回答