Monday, February 21, 2011

how to read data from xml file

<?xml version="1.0" encoding="utf-8" ?> 
<user>
  <username>prince</username> 
  <password>user1</password> 
</user>

This is my xml file name as user.xml.

Now when i click the button in the page, i need to get the data from that file and place that data in variable like:

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

Can anyone tell me how to do this with syntax?

thank you

From stackoverflow
  • LINQ to XML is the modern way to do what you want, see here

     XDocument xDoc = XDocument.Load("user.xml");
     string strusername =  xDoc.Descendants(XName.Get("username")).First().Value;
     string strPassword = xDoc.Descendants(XName.Get("password")).First().Value;
    
    Jon Skeet : Any reason for using XName.Get instead of just using the implicit conversion from string? `Descendants("username")`...
    ArsenMkrt : Descendants doesn't have version that take string as an argument, isn't it?
    marc_s : Works great, if you're on .NET 3.5 and up - use XmlDocument on .NET 3.0 and below
    prince23 : thank you ArsenMkrt
  • You could try something like the XmlReader, XmlTextReader and XmlDocument. They are all relatively straight forward to use.

0 comments:

Post a Comment