如何从XML文件中读取和修改数据?

时间:2013-05-05 10:14:26

标签: c# .net xml exception-handling

请给我最简单的方法来阅读或修改XML文件数据?

目前我尝试了这个,但它抛出异常。我目前的代码是:

 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;
 }

我的XML如下:

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

和例外是:

  

NullReference异常:“对象引用未设置为对象的实例。”

我该怎么办?

答案:我纠正了问题中的代码。          现在它是100%正确的。

2 个答案:

答案 0 :(得分:4)

当您选择addresh时,您的XML文件会显示address

答案 1 :(得分:-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;

    }

}