Parse xml elements and their attributes in LINQ

QuynhKr

New Member
Today is the first time I ever expose to LINQ so to say I am newbie is an understatement.. So what I am trying to do is to parse the value of the STAT elements and their attributes. My sample XML looks like this.\[code\]<ILS TGT="00-25-CE-94-00-05" PID="404001C5354144E4DA40E01F5000002" ORGCODE="00010019" xmlns="Mytest/v1.0"> <STAT TIME="000000018" TYPE="SYS" FIELD="PWR_V" VAL="1196"/> <STAT TIME="000000018" TYPE="CAN" NID="65" FIELD="LAST_EC" VAL="EC_HEARTBEAT_TIMEOUT"/> <STAT TIME="000000018" TYPE="NWK" FIELD="W_RSSI" VAL="-85"/> <EVT TIME="0000000017" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DPIN" CRED1="1212"/> <EVT TIME="0000000018" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DPIN" CRED1="1212" CRED2="2345"/> <EVT TIME="0000000019" TYPE="ACC" SUBTYPE="DENIED" CRDT="OCRD" CRED1="0000DE0871"/> <EVT TIME="0000000020" TYPE="ACC" SUBTYPE="GRANTED" CRDT="DCRD" CRED1="0000DE0871" CRED2="2345"/> <EVT TIME="0000000021" TYPE="CFG" SUBTYPE="RELOCK_TIME" VAL="300"/> <EVT TIME="0000000022" TYPE="LOG" SUBTYPE="HB_TIMEOUT" VAL="65"/></ILS>\[/code\]So upon searching around on this board I found the following question which answers my question. However, I applied that and for some reason I can't get any result at all, can anybody take a quick look and point to what I have done wrong?\[code\]public static void ParseXML(string data) { try { XDocument xDoc = XDocument.Parse(data); XElement root = xDoc.Root; Console.WriteLine("TGT: " + root.Attribute("TGT").Value + "\n"); Console.WriteLine("PID: " + root.Attribute("PID").Value + "\n"); Console.WriteLine("ORGCODE: " + root.Attribute("ORGCODE").Value + "\n"); Console.WriteLine("xmlns: " + root.Attribute("xmlns").Value + "\n"); //Everything above this line is good, I was able to get the print out. var eleSTAT = from node in xDoc.Descendants("STAT") select new { attrTIME = node.Attribute("TIME").Value, attrTYPE = node.Attribute("TYPE").Value, attrFIELD = node.Attribute("FIELD").Value, attrVAL = node.Attribute("VAL").Value, }; //When I run my code, it never got into this foreach loop, aas if eleSTAT is empty foreach (var s in eleSTAT) { Console.WriteLine("TIME: " + s.attrTIME + "\n"); Console.WriteLine("TYPE: " + s.attrTYPE + "\n"); Console.WriteLine("FIELD: " + s.attrFIELD + "\n"); Console.WriteLine("VAL: " + s.attrVAL + "\n"); } } catch (Exception ex) { Console.WriteLine(ex); } }\[/code\]And my last question, since I have multiple STAT element, would the above work? I want to have all 4 STAT elements and their attributes return to me. I figure this has to be done in some type of loop? am I correct in saying my foreach loop should already does this?
 
Back
Top