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

本文关键字:修改 数据 读取 XML 文件 | 更新日期: 2023-09-27 18:12:15

请给我最简单的方法来读取或修改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>   

和Exception是:

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

我该怎么办?

答:我更正了问题中的代码。

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

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

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