Search code examples
.net-2.0xmlreader

How can I read all elements in a plain XML using XMLReader in .Net 2.0?


I have the following XML:

<XMLDictionary>
  <a>b</a>
  <c>d</c>
  <e>f</e>
</XMLDictionary>

I'm trying to get the mappings a: b, c: d, e: f, and I can't quite find how to do it simply.

My current code looks like this:

    Do While reader.Read()
        If reader.NodeType = Xml.XmlNodeType.Element Then
            Me.Add(reader.Name, reader.ReadElementString)
        End If
    Loop

The problem is that I don't know how to read the contents of the element without calling ReadElementString, and ReadElementString advances the "pointer" to the next node (so reader.Name already has the next value). When in the loop I call Read() again, i'm skipping nodes.
I've tried several variations on this theme, and none works perfectly, which indicates that i'm missing something important here.

Any pointers?

Thanks


Solution

  • I don't know if I would use the XmlReader for what you are doing, probably just an XmlDocument, but if you want the reader, probably something like this might work:

    Dim lastNode As String = string.Empty
    Do While reader.Read()
         If reader.NodeType = Xml.XmlNodeType.Element Then
            lastNode = reader.Name
         Else If reader.NodeType = Xml.XmlNodeType.Text AND NOT string.IsNullOrEmpty(lastNode) THEN
             Me.Add(lastNode,reader.Value)
             lastNode = string.Empty    
         End If
    Loop
    

    Forgive me for any syntax errors; it's been a while since of written in VB.net. This is a basic state machine that first detects if an Element is found and then starts looking for a text value.