Query XML With LINQ to Populate an asp:Repeater from Attribute Values

by Duane Urban 13. February 2013 06:10

I'll let the code do the talking with this LINQ query on an XML file.

First the XML:

<?xml version="1.0" encoding="utf-8" ?>
<DirectSmileSets>
  <Set ID="1" Name="BeerGlass" DisplayName="Beer Glass">
    <Size>
      <Width>300</Width>
      <Height>200</Height>
      <Resolution>72</Resolution>
    </Size>
    <Variables>
      <Variable Name="FirstName" DisplayName="First Name" AllowSplit="False"></Variable>
      <Variable Name="LastName"  DisplayName="Last Name" AllowSplit="False"></Variable>
    </Variables>
  </Set>
  <Set ID="2" Name="Leaves" DisplayName="Leaves">
    <Size>
      <Width>300</Width>
      <Height>200</Height>
      <Resolution>72</Resolution>
    </Size>
    <Variables>
    <Variable Name="FirstName" DisplayName="First Name" AllowSplit="False"></Variable>
    </Variables>
  </Set>
  <Set ID="3" Name="Billboard"  DisplayName="Billboard">
    <Size>
      <Width>300</Width>
      <Height>200</Height>
      <Resolution>72</Resolution>
    </Size>
    <Variables>
    <Variable Name="FirstName" DisplayName="First Name" AllowSplit="False"></Variable>
    <Variable Name="LastName"  DisplayName="Last Name" AllowSplit="False"></Variable>
    </Variables>
  </Set>
</DirectSmileSets>

 

Requirement:

Populate a repeater with the "Variable Name" values under a selected "Set".

The LINQ query:

 

        /// <summary>
        /// Gets child records under the "Variables" element and populates a repeater
        /// </summary>
        /// <param name="parentId">The "Set" ID attribute</param>
        protected void BindVariableRepeater(string parentId)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("DisplayName", typeof(string));
           
            XDocument root = XDocument.Load(DMEFramework.DMEUtilities.xmlFileLocation());
            var rec = from c in root.Descendants("Set")
                      where c.Attribute("ID").Value == "" + parentId + ""
                      select new
                      {
                          Variables = c.Elements("Variables")
                      };

            foreach (var obj in rec)
            {
                foreach (var variables in obj.Variables)
                {
                    foreach (var item in variables.Elements("Variable"))
                    {
                        // Add rows to a DataTable for the repeaters datasource
                        dt.Rows.Add(item.Attribute("DisplayName").Value);
                    }
                }
            }

            this.lblSelectedSet.Text = "Selected Set";
            this.rptVars.DataSource = dt;
            this.rptVars.DataBind();

        }

 

Tags: , ,

ASP.NET | LINQ | XML

Pingbacks and trackbacks (4)+