Click here to Skip to main content
11,417,972 members (42,355 online)
Click here to Skip to main content

LINQ to XML to retrieve an element value by its attribute

, 27 Jul 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Using LINQ to XML to retrieve an element value by its attribute.

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:

  1. The XML file "Actions.xml":
  2. <?xml version="1.0" encoding="utf-8" ?>
    <Actions>
    <Action id="SignIn">1</Action>
    <Action id="SignOut">2</Action>
    <Action id="Open">3</Action>
    </Actions>
  3. The class "Actions.cs":
  4. 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.

  5. The code behind the webpage to call the method is shown here:
  6. 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dev. Action
Software Developer (Senior)
Egypt Egypt
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 Pin
heracles maroudas8-Jul-11 0:58
memberheracles maroudas8-Jul-11 0:58 
Generalhave a nested element f, seems Im wiriting the xmlDocument.Elements("StreetName") incorrect cant get a result Pin
69stephen29-Aug-10 5:13
member69stephen29-Aug-10 5:13 
Im using LINQ to XML I have the xml I've retrieved from a server. here is the link to the file listing.xml

but for whatever reason I dont seem to be able pull just the node i want form the file the result of the query is always null
here is the code snippet
 
 
string queryURI = "http://retsgw.flexmls.com/rets2_0/Search?SearchType=Property&Class=A&QueryType=DMQL2&Query=(LIST_105=4123192)&Count=0&Format=STANDARD-XML&StandardNames=0&RestrictedIndicator=****&Limit=1@Select=LIST_105";
        HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(queryURI);
        req2.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        req2.Credentials = new NetworkCredential("------", "-------"); //This line ensures the request is processed through Basic Authentication
        req2.ContentType = "text/xml" ;
        req2.Accept = "text/xml" ;
        req2.Method = "Post" ;
        HttpWebResponse response = (HttpWebResponse)req2.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string xml = reader.ReadToEnd();
 
       
            XDocument listing = XDocument.Parse(xml);
         
           
        clsStreetAddress streetAddress = (from s in listing.Elements("StreetAddress")
                                                select new clsStreetAddress
                                                {
                                                    streetNumber = s.Element("StreetNumber").Value,
                                                    streetDirPrefix = s.Element("StreetDirPrefix").Value,
                                                    streetName = s.Element("StreetName").Value,
                                                    streetSufix = s.Element("StreetSufix").Value,
                                                    unitNumber = "4",
                                                    City = s.Element("City").Value,
                                                    PostalCode = s.Element("PostalCode").Value
                                                }).SingleOrDefault();
 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150427.4 | Last Updated 27 Jul 2009
Article Copyright 2009 by Dev. Action
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid