2

Please give me the simplest way to read or modify the XML file data?

Currently I tried this but it throws an exception. My current code is:

 XmlDocument xml = new XmlDocument();
 xml.Load("server.xml");

 XmlNodeList serverlist = xml.SelectNodes("//server");
 foreach (XmlNode servernodes in serverlist)
 {
      string server_address = servernodes.SelectSingleNode("addresh").InnerText;
      string server_uname = servernodes.SelectSingleNode("username").InnerText;
      string server_psw = servernodes.SelectSingleNode("password").InnerText;
 }

my XML is below:

<?xml version="1.0" ?>
<server>
<address>localhost</address>
<username>myuser</username>
<password>mypassword</password>
</server>   

and Exception is:

NullReference Exception: "Object reference not set to an instance of an object."

What should i do?

Answer : I am correcteed the code in Question. Now it is 100% right.

Vimesh Shah
  • 89
  • 2
  • 13

2 Answers2

4

You XML files says addresh while you are selecting address.

Martin Mulder
  • 11,592
  • 3
  • 19
  • 50
-1
class ServerFunction {
    public string LocalHost;
    public string User;
    public string Pass;

    //Copy Constructor
    public ServerFunction(ServerFunction obj)
    {
        LocalHost = obj.LocalHost;
        User = obj.User;
        Pass = obj.Pass;
    }

    //Constructor
    public MemberFunction()
    {
        LocalHost = null;
        User = null;
        Pass = null;
    }

}

//Object of the Class
ServerFunction func = new ServerFunction(); 

static void Main(string[] args)
{
    XmlDocument xml = new XmlDocument();
    xml.Load("server.xml");

    XmlElement root = xmlDoc.DocumentElement;
    foreach (XmlNode node in root.ChildNodes)
    {
                func.LocalHost = node.Attributes["address"].Value;
                func.User = node.Attributes["username"].Value;
                func.Pass = node.Attributes["password"].Value;

    }

}
M. Haris Azfar
  • 480
  • 4
  • 15