Search code examples
xmlvb.netstreamreader

read an xml stream


I am trying to read the following xml stream but am really struggling.

<channelSnapshot xmlns="urn:betfair:games:api:v1">
<channel gameType="BLACKJACK" id="1444077" name="Exchange BlackJack">
<status>RUNNING</status>
<game id="190675">
<round>1</round>
<bettingWindowTime>30</bettingWindowTime>
<bettingWindowPercentageComplete>100</bettingWindowPercentageComplete>
<gameData>
<object name="Player 1">
<description/>
<status>IN_PLAY</status>
<property name="Card 1" value="NOT AVAILABLE"/>
<property name="Card 2" value="NOT AVAILABLE"/>
</object>

The stream is acquired in the following way

  Dim dataStream As Stream = response.GetResponseStream()
  Dim reader As New XmlTextReader(dataStream)

If the element is between a start tag and end tag such as

 <status>RUNNING</status>

Then I can access the value ok. I have been using Select Case xmlnodetype but using this when the nodetype is a whitespace I can't get to the element beyond the whitespace.So that in the following line

 <property name="Card 1" value="NOT AVAILABLE"/>

I cant get to anything beyond the word property.

As must be obvious this is all new to me, so I would welcome all and any help.


Solution

  • How about a different approach? Processing the stream as you are currently doing seems to be pretty hard work.

    If you instead read the whole stream into a string and then load that string into an XDocument you'll be able to process the file much easier.

    VB allows you to access data from Xml files in a very easy way, take a look at the following code to see what I mean:

    ' get the response stream so we can read it
    Dim responseStream = response.GetResponseStream()
    ' create a stream reader to read the response
    Dim responseReader = New IO.StreamReader(responseStream)
    ' read the response text (this should be javascript)
    Dim responseText = responseReader.ReadToEnd()
    
    ' load the response into an XDocument
    Dim xmlDocument = XDocument.Parse(responseText)
    
    ' find all the player objects from the document
    For Each playerObject In xmlDocument...<object>
    
        ' display the player's name (this is how you access an attribute)
        Console.WriteLine("Player name: {0}", playerObject.@name)
        ' display the player's status (this is how you access an element)
        Console.WriteLine("Player status: {0}", playerObject.<status>.Value)
    
    Next
    

    To get your player properties you can do the following:

    ' go through the player's properties
    For Each playerProperty In playerObject...<property>
        ' output the values
        Console.WriteLine("Player property name: {0}", playerProperty.@name)
        Console.WriteLine("Player property value: {0}", playerProperty.@value)
    Next
    

    As somebody else mentioned, your Xml is malformed, but the XDocument will tell you about this so you'll be able to fix it.