2

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

4

2 回答 2

4

您的 XML 文件addresh在您选择时显示address

于 2013-05-05T10:28:02.407 回答
-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;

    }

}
于 2013-05-05T10:42:23.877 回答