read from xml by tag in c#

agile's Avatar, Join Date: Sep 2010
Newbie Member
hi

i am new to c# and xml. i have made a xml file by c# where the tags are Information,Fname,Lname,Username.

now i want to read value from Fname tag and set the value in a text box.
i also want to read value from Lname tag and set the value in a text box

how can i do this.

agile
0
dotNet Zombie's Avatar, Join Date: Aug 2010
Go4Expert Member
In the .Net there is a Namespace called XML where you can grab the Class XmlDocument.

Code:
XmlDocument xmlDoc = new XmlDocument();
and use a method called LoadXml(string xml) to load the xml into the XmlDocument Object.

When the Xml is loaded into the XmlDocument object you can view it's attributes and element using the properties inside the XmlDocument.

For more info see MSDN Documentation on XmlDocument: msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx
shabbir like this
0
muthuis's Avatar, Join Date: Oct 2010
Go4Expert Member
There is another interesting feature in C# namely XML Serialization. You can read from / to a class to / from xml. A convenient way of using C# for reading and writing xml data.
0
blackrubybarb's Avatar, Join Date: Oct 2010
Light Poster
Quote:
Originally Posted by agile View Post
hi

i am new to c# and xml. i have made a xml file by c# where the tags are Information,Fname,Lname,Username.

now i want to read value from Fname tag and set the value in a text box.
i also want to read value from Lname tag and set the value in a text box

how can i do this.

agile
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"your_xml_file_Path.xml");
XmlNodeList Fname = xDoc.GetElementsByTagName("Fname");
XmlNodeList Lname = xDoc.GetElementsByTagName("Lname");
textBox1.Text = Fname[0].InnerText;
textBox2.Text = Lname[0].InnerText;
0
mail.yuva's Avatar, Join Date: Jan 2011
Go4Expert Member
Sample coding snipet for Reading xml Using LINQ to XML conceptws

Code:
//namespace

using System.Linq;
using System.Xml.Linq;

public IQueryable ReadXML(string Filepath)
        {
            XDocument doc = XDocument.Load(Filepath);

            var Result = doc.Descendants("Employee").Select(a =>
                new
                {
                    FirstName = a.Element("Fname").Value,
                    LastName = a.Element("LastName").Value,
                    Age = a.Element("Age") != null ? a.Element("Age").Value : "0",
                    Salary = a.Element("Salary").Value,
                    }).AsQueryable();

            return Result;
        }

Last edited by shabbir; 10Jan2011 at 16:47.. Reason: Code blocks