Alen
Alen

Reputation: 1291

Cannot add to node in XML

I have a Model in C# winforms named User and it has a code to add in an xml file.

class User
{
    public string Username { get; set; }

    public void AddUserXml()
    {
        XmlDocument xml = new XmlDocument();

        xml.Load("user.xml");
        XmlNode x = xml.SelectSingleNode("/username");
        x.InnerText = Username;
        xml.Save("user.xml");
    }
}

in main class I am trying to call it like

User user = new User();
user.Username = "test";
user.AddUserXml();

But this gives this error

An unhandled exception of type 'System.NullReferenceException' occurred. Additional information: Object reference not set to an instance of an object.

My XML looks like this

<?xml version="1.0" encoding="utf-8"?>
    <user>
      <username></username>
      <course></course>
    </user>

Upvotes: 0

Views: 78

Answers (2)

Dominik
Dominik

Reputation: 1741

The topmost tag in your xml is the "user" tag not the "username" tag. This is why you need to select the user-node first and then select the username-node of the user-node.

Furthermore you need to select "username" not "/username"

public void AddUserXml()
{
    XmlDocument xml = new XmlDocument();
    xml.Load("user.xml");                
    var userNode = xml.SelectSingleNode("user");
    var userNameNode = userNode.SelectSingleNode("username");
    userNameNode.InnerText = Username;
    xml.Save("user.xml");
}

Upvotes: 0

Dave
Dave

Reputation: 3017

Your call to SelectSingleNode you are passing "/username" that is not the name of the node the, it should be "username". Because it can't find a node by the name of "/username" it returns null and then you try and access a property of a null object and bang there's your exception

Upvotes: 1

Related Questions