2013-05-05 45 views
2

請給我最簡單的方式來閱讀或修改XML文件數據?如何從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%正確。

+0

你不必叫「//服務器」或「地址」的任何節點 – Sayse 2013-05-05 10:17:37

+0

服務器是我的根節點 – 2013-05-05 10:18:39

+0

編輯對不起,我誤會的selectNodes功能。地址仍然丟失,雖然 – Sayse 2013-05-05 10:18:58

回答

4

當您選擇address時,您的XML文件顯示爲addresh

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

    } 

} 
+0

-1:他有元素,而不是屬性,你的代碼有同樣的問題 – 2013-05-07 10:45:27