Introduction
This article tells us how to retrieve a value of an element depending on the attribute value.
The Scenario
I have a web site where I need to read some data as static but I want to be able to update it any time, so I decided to read it from an XML file and use LINQ to XML. After some time and a lot of searching here and there, I had a better understanding of the idea and so I decided to share it with every one.
Using the Code
We will make an XML file and a class to get the data from it:
- The XML file "Actions.xml":
="1.0"="utf-8"
<Actions>
<Action id="SignIn">1</Action>
<Action id="SignOut">2</Action>
<Action id="Open">3</Action>
</Actions>
- The class "Actions.cs":
We will make the class constructor the one which gets the data to our variables in the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
public class Actions
{
int signIn, signOut, open;
public int SignIn
{
get { return signIn; }
}
public Actions()
{
XElement xe = XElement.Load(@"C:\Users\ADELOooO\Documents\
Visual Studio 10\WebSites\LinQReadXML\Actions.xml");
var x = from a in xe.Elements("Action")
Where a.Attribute("id").Value == "SignIn"
select a.Value;
signIn = int.Parse(x.First().ToString());
}
}
We have used the signin
variable as an example above, but you can use it with them all.
- The code behind the webpage to call the method is shown here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Actions a = new Actions();
TextBox1.Text = a.SignIn.ToString();
}
}
Points of Interest
I used VSTS 10 beta to create this project. I hope that you find it helpful.