XML to LinQ best practice RRS feed

  • Question

  • Hello,
    What is the best way to read from an element, the sub-elements that are available to me in a list?
    If you have a wide branching, depth, how best to select quickly a element with attributs?
    	<STEP value="Step1" />
    	<STEP value="Step2">
    		<ACTIVE value="1" />
    		<PRINT value="1" />
    		<ACTIVE value="1" />
    		<OVERDRAW value="6" />
    	<STEP value="STEP4">
    		<ACTIVE value="0" />
    		<DELETE_IN_DAYS value="110" />
    Like this
    List<Process> listProcess
        class PROCESS 
    	   class STEP
    	     <ACTIVE value="1" />  
    	     <OVERDRAW value="6" />   for that can be anything. 
    Maybe in a dictionary Element is key name, value is the value.
    Thanks in advance for good tips.
    Best regards Markus

    Thursday, October 24, 2019 4:45 PM


  • Hi Markus,

    Thank you for posting here.

    Based on your description, you want to select quickly a element with attributes and put them into a dictionary.

    You can refer to the following code.

     XDocument doc = XDocument.Load("D:\\1.xml");
                var result = doc.Descendants("STEP").Where(x => x.HasElements);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (var item in result)
                    string firstkey = ((XElement)item.FirstNode).Name.LocalName;
                    string firstvalue = ((XElement)item.FirstNode).Attribute("value").Value;
                    string seondkey = ((XElement)item.LastNode).Name.LocalName;
                    string secondvalue = ((XElement)item.LastNode).Attribute("value").Value;
                        dic.Add(firstkey, firstvalue);
                    if (!dic.ContainsKey(seondkey))
                        dic.Add(seondkey, seondvalue);


    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Friday, October 25, 2019 8:58 AM