Tuesday, June 21, 2011

Using DataContractSerializers with the Eve Online API

After browsing the Eve Online forums I came across a project someone was writing in VB.NET to make their industry life easier.

The problem, I thought, was that they weren't treating the response from the API as an object which made it difficult to read the code and debug it. I got to thinking, and came up with this bit of code to parse the Characters.xml response. You just have to construct the class with the response you get after you call Characters.xml.

Imports System.IO

Imports System.Xml.Schema
Imports System.Xml.Serialization
Imports System.Runtime.Serialization

Public Class xmlParser
Public api As eveapi

Public Sub New(ByVal eveApiXmlResponse As String)
api = parseXml(eveApiXmlResponse)

For Each charList As characterList In api.characterLists
For Each eveChar As eveCharacter In charList.characters
End Sub

Private Function parseXml(ByVal eveResponse As String) As eveapi
Dim xmlRoot As XmlRootAttribute = New XmlRootAttribute
xmlRoot.ElementName = "eveapi"
xmlRoot.IsNullable = True
Dim serializer As New XmlSerializer(GetType(eveapi), xmlRoot)
Dim ms As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(eveResponse))

Return CType(serializer.Deserialize(ms), eveapi)
End Function
End Class

Partial Public Class eveapi
Public Property currentTime As String
Public Property cachedUntil As String

<System.Xml.Serialization.XmlArrayAttribute("result", Form:=XmlSchemaForm.Unqualified), _
System.Xml.Serialization.XmlArrayItemAttribute("rowset", GetType(characterList), Form:=XmlSchemaForm.Unqualified)> _
Public Property characterLists As List(Of characterList)

Public Property version As String

End Class

<XmlTypeAttribute(AnonymousType:=True)> _
Partial Public Class characterList
<System.Xml.Serialization.XmlElementAttribute("row", Form:=XmlSchemaForm.Unqualified)> _
Public Property characters As List(Of eveCharacter)

Public Property name As String
Public Property key As String
Public Property columns As String
End Class

<XmlTypeAttribute(AnonymousType:=True)> _
Partial Public Class eveCharacter

<XmlAttributeAttribute()> _
Public Property name As String

<XmlAttributeAttribute()> _
Public Property characterID As String

<XmlAttributeAttribute()> _
Public Property corporationName As String

<XmlAttributeAttribute()> _
Public Property corporationID As String

End Class

No comments:

Post a Comment