Click here to Skip to main content
14,426,749 members
Rate this:
Please Sign up or sign in to vote.
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;



//****** 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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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

var objCases = (from C in objDoc.Descendants("Case")
                     where C.Attribute("Compartment").Value == "1"
                     select C).ToList();
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100