2009-10-09 162 views
2
<?xml version="1.0" encoding="utf-8" ?> 
<user> 
    <username>prince</username> 
    <password>user1</password> 
</user> 

这是我的xml文件名称user.xml。如何从xml文件读取数据

现在,当我在页面上点击按钮,我需要从文件中获取数据,并将这些数据在像变量:

string strusername = data cmg from xml file (prince) 
string strPassword = data cmg from xml file (password) 

谁能告诉我如何与语法做到这一点?

谢谢

回答

6

LINQ to XML是做你想要的现代生活方式。

XDocument xDoc = XDocument.Load("user.xml"); 
string strusername = xDoc.Descendants(XName.Get("username")).First().Value; 
string strPassword = xDoc.Descendants(XName.Get("password")).First().Value; 
+0

任何使用XName.Get的原因而不是仅仅使用字符串的隐式转换? '后代(“用户名”)'...... – 2009-10-09 07:47:50

+0

后代没有将字符串作为参数的版本,不是吗? – 2009-10-09 08:07:23

+0

很好,如果你使用.NET 3.5或更高版本 - 在.NET 3.0和以下使用XmlDocument – 2009-10-09 08:58:22