如何从xml文件中读取数据

hap*_*ile 2 xml asp.net

<?xml version="1.0" encoding="utf-8" ?> 
<user>
  <username>prince</username> 
  <password>user1</password> 
</user>
Run Code Online (Sandbox Code Playgroud)

这是我的xml文件名user.xml.

现在,当我单击页面中的按钮时,我需要从该文件中获取数据并将该数据放在变量中,如:

string strusername =  data  cmg from  xml file (prince)
string strPassword =  data  cmg from  xml file (password)
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我如何使用语法执行此操作?

谢谢

Ars*_*yan 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;
Run Code Online (Sandbox Code Playgroud)