views:

31

answers:

2

I am developing asp.net mobile application. I am using LINQ to XML to query XML file. I am using the following query to retrieve the name & value of the query dynamically as follows

var TotalManifolds = from MF in FieldRoot.Element("FIELD-DEFINITION").Element("MANIFOLDS").Elements("MANIFOLD")
                     join SLT in FieldRoot.Element("FIELD-DEFINITION").Element("SLOTS").Elements("SLOT")
                     on (string)MF.Attribute("MID") equals (string)SLT.Attribute("PARENT")
                     select new
                     {
                         SlotName = (string)SLT.Attribute("NAME").Value,
                         SlotValue = (string)SLT.Attribute("NAME").Value
                     };

In the following statement of above query I want to retrive the name of the attribure dynamically without explicitly specifying the name of the attribute SlotName = (string)SLT.Attribute("NAME").Value Here I am explicitly specifying the name. I want to code which can dynamically retrieve the name of the attribute. I am new to Linq to xml. Can you please tell how this can be done programatically ? or can you provide me the link through which I can resolve the above issue ?

A: 

If I understand you correctly, you could always pass a variable in to the LINQ query:

var string attrName = "NAME";  // specify whatever value you need ...

// wrap the query below in a function, if it will be reused...
var TotalManifolds = from MF in FieldRoot.Element("FIELD-DEFINITION").Element("MANIFOLDS").Elements("MANIFOLD")  
                 join SLT in FieldRoot.Element("FIELD-DEFINITION").Element("SLOTS").Elements("SLOT")  
                 on (string)MF.Attribute("MID") equals (string)SLT.Attribute("PARENT")  
                 select new  
                 {  
                     SlotName = (string)SLT.Attribute(attrName).Value,  
                     SlotValue = (string)SLT.Attribute(attrName).Value  
                 }; 
LBushkin
A: 

It seems you are looking for something like:

// ...
select new
{
    SlotName = SLT.Attributes().First().Name,
    SlotValue = SLT.Attributes().First().Value
};
kbrimington