Question

I have a sample xml

<Lookup> 
    <Controller Name="Activity1" >
       <action Name="Editactivity1" appgroup="Something" productcode="SomethingElse"/>    
    </Controller> 
    <Controller Name="Activity2">    
       <action Name="Editactivity2" appgroup="Something1" productcode="SomethingElse2"/>  
    </Controller>
</Lookup>

I have the controller name and action name stored in variables.

var cntName;
var actName;

Based on these values I have to look up this Xml and fetch the corresponding appgroup and productcode values.

Note: example values for cntName would be Activity1 or Activity2 or ActivityN.
Example values for actName would be EditActivity1 or EditActivity2 or EditActivityN.

So based on these values i have to look up the xml, Hope I am clear with my problem statement.

I am reading my xml using traditional xmldatadocument, how do i change it to LINQ? Sample below.

XmlDocument xmlDocAppMod = new XmlDocument();
strFileName = System.Configuration.ConfigurationManager.AppSettings["AppModOptListPath"].ToString();
strFileLocation = System.Web.HttpContext.Current.Server.MapPath("~/" + strFileName);

xmlDocAppMod.Load(strFileLocation);

Thanks, Adarsh

Was it helpful?

Solution

Basically, you have several options:

  1. Load the document from disk and create an xPath expression to evaluate it:

    var doc = new XmlDocument();
    doc.Load(fileName);
    var node = doc.SelectSingleNode(
        string.Format("/Lookup/Controller[@Name='{0}']/action[@Name='{1}']", cntName, actName));
    
    if (node != null)
    {
    
            var appGroup = node.Attributes["appgroup"].Value;
            var productcode = node.Attributes["productcode"].Value;
    }
    
  2. Another option could be to use XDocument:

        var doc = XDocument.Load("");
        var action = doc.Descendants("Controller")
            .Where(c =>
                       {
                           var controllerName = c.Attribute("Name");
                           return controllerName != null && controllerName.Value.Equals(cntName);
                       })
            .FirstOrDefault()
            .Elements("action")
            .Where(a =>
                       {
                           var controllerName = a.Attribute("Name");
                           return controllerName != null && controllerName.Value.Equals(actName);
                       })
            .FirstOrDefault();
        var appGroup = action.Attribute("appgroup").Value;
        var productCode = action.Attribute("productcode").Value;
    

UPDATE:

Of course, you could use xPath with Linq-to-XML as well:

var doc = XDocument.Load("");
var action = (XElement) doc.XPathEvaluate(string.Format("/Lookup/Controller[@Name='{0}']/action[@Name='{1}']", cntName, actName));
var appGroup = action.Attribute("appgroup").Value;
var productCode = action.Attribute("productcode").Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top