XmlReader question -- reading nested elements


  • I have an XmlReader that's passed to a method while it's at the very beginning of an element elem1.

    ...Rest of document...
    <elem1 attr1="val1" attr2="val2">
       <elem2 attr3="val3" />
       <elem2 attr4="val4" attr5="val5" />
       <elem2 attr6="val6" attr7="val7" />
    ...Rest of document...

    Here's what I want to do but can't figure out how to:

    1. Stop processing immediately if the XmlReader is NOT at an <elem1> element with zero or more nested <elem2> elements. There

    should be no other nested elements.

    2. Read in elem1 and all its attributes. (I can do this.)

    3. Read in all nested elem2 elements, one by one, and their attributes, one by one.

    4. Stop processing after the current elem1 element has been successfully processed.
    Tuesday, February 21, 2006 5:00 AM


All replies

  • Have you considered using serialization instead? 

    That is, use the xsd program to generate a schema from your xml file (modify the schema if necessary - often not, if you choose an xml file which is rather complete).  The use the xsd program again, this time on the schema file with the /c option to generate a serializable class.  Read in the data using any streamreader and the generated class, and the class is then filled with all the data of your file.  Now you can process it any way you want, and move the data over to your other structure, whatever that is.


    Wednesday, February 22, 2006 4:08 PM
  • Here's another suggestion you might try:

    Instead of passing in the XmlReader, do a SelectNodes or a SelectSingleNode for just the <elem1>, and then you can just pass in the nodes you want to process.


    Wednesday, February 22, 2006 4:37 PM
  • Just use a XmlDocument and load you Xml in it with the XmlDocument.Load or XmlDocument.LoadXml method.

    Then try to select you <elem1 node with the XmlDocument.SelectSingleNode method and when it doesn't return null, it exists and you can process it. Otherwise just stop processing.
    Thursday, February 23, 2006 8:47 AM