none
Traversing XML

    Question

  • I have the following xml:

    <Student>
       <questions>
         <question>
            <prompt>Where do you live?</prmpt>
            <answer>grandparents</answer>
            <answer>mom</answer>
            <answer>dad</answer>
            <answer>friend</answer>
            <answer>cousin</answer>
         </question>
         <question>
            <prompt>Where do you live?</prmpt>
            <answer>grandparents</answer>
            <answer>mom</answer>
            <answer>dad</answer>
            <answer>friend</answer>
            <answer>cousin</answer>
         </question>
         <question>
            <prompt>Where do you live?</prmpt>
            <answer>grandparents</answer>
            <answer>mom</answer>
            <answer>dad</answer>
            <answer>friend</answer>
            <answer>cousin</answer>
         </question>
       </questions>
    </Student>

     

    I want to traverse the documet such that  I can assign to a string and or list Each seperate innertext value from the <answer> tag.  I'm not sure how to iterate through the child nodes of the <question> parent tag such that I can list all the available answers to a asp.net web page.

    Thank you!

    Wednesday, May 11, 2011 8:33 PM

Answers

All replies

  • If your document is always this short, you can do it pretty easily with the LINQ to XML classes.

    XDocument doc = XDocument.Load(myXmlString);
    
    foreach (XElement answerElement in doc.XPathSelectElements("/Student/questions/question/answer"))
    {
     myList.Add(XElement.Value);
    }
    
    

    EDIT: Fixed a couple of typos, and fixed the XPath to go to the answer node.

    Wednesday, May 11, 2011 8:39 PM
  • Hi Tim,

     

    Thank you for the response  I've tried using the using System.Xml.XPath;  and with that I tried to implement your code snippet and for some strange reason the XPathSelectElements() method is not listed!  Not sure if I missed anything.

     

    QT

    Wednesday, May 11, 2011 9:05 PM
  • Try using the namespace System.Linq.Xml

    • Marked as answer by QuickTrick Tuesday, May 17, 2011 10:22 PM
    Wednesday, May 11, 2011 9:12 PM
  • Any update? Would you mind letting us know how it goes? Was your question solved?

    Best Regards,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, May 12, 2011 8:00 AM