Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从XML文件中读取和修改数据?_C#_.net_Xml_Exception Handling - Fatal编程技术网

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

C# 如何从XML文件中读取和修改数据?,c#,.net,xml,exception-handling,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 = se

请告诉我读取或修改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%正确。

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

您没有任何名为“//server”的节点,或者“address”服务器是我的根节点。抱歉,我误解了selectnodes函数。地址仍然丢失,所以我会在代码中做什么更改?欢迎使用堆栈溢出!几乎所有
NullReferenceException
的情况都是相同的。请参阅“”,以获得一些提示。-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;

    }

}