Click here to Skip to main content
15,901,853 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can anyone tell me any optimization for following LINQ to XML-
(Query retrieves all Case node having Compartment==1)
System.Xml.Linq.XDocument objDoc = System.Xml.Linq.XDocument.Load("ABC.xml");
            var objCases = from C in objDoc.Descendants("Case")
                           where C.Parent.Name.ToString().Trim() == "cases"
                            && C.Parent.Parent.Name.ToString().Trim() == "Data"
                            && C.Attribute("Compartment").Value.Trim() == "1"
                           select C;
            List<string> Lst_ExistingCase = new List<string>();
            foreach (var xCase in objCases)
            {
                if (xCase.Attribute("Id") != null)
                    Lst_ExistingCase.Add(xCase.Attribute("Id").Value.Trim());
            }
            objDoc = null;



XML
//****** ABC.xml ******************
<Data>
  <cases>
    <Case Id="A" Compartment="1" />
    <Case Id="B" Compartment="2"/>
    <Case Id="C" Compartment="3"/>
    <Case Id="D" Compartment="1"/>
    <Case Id="E" Compartment="2"/>
    <Case Id="F" Compartment="3"/>
    <Case Id="G" Compartment="1"/>
  </cases>
 </Data>
 //********************************
Posted

1 solution

Please try this.

System.Xml.Linq.XDocument objDoc = System.Xml.Linq.XDocument.Load(HttpContext.Server.MapPath("XMLFile.xml"));

var objCases = (from C in objDoc.Descendants("Case") 
                where C.Attribute("Compartment").Value == "1"
                select C.Attribute("Id").Value).ToList();

            foreach (var Ids in objCases)
            {
                 Console.WriteLine(Ids);
            }


And if you want to select all Case Node then you can use this

SQL
var objCases = (from C in objDoc.Descendants("Case")
                     where C.Attribute("Compartment").Value == "1"
                     select C).ToList();
 
Share this answer
 
v6
Comments
RhishikeshLathe 23-Dec-13 7:19am    
you just removed my validation part...?

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900