Type Conversion

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Given the following XML document:<br/>
<div id="x_code
<h4>CODE</h4>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><br/>
<ISO_CCY_CODES><br/>
<ISO_CURRENCY><br/>
<ENTITY>AFGHANISTAN</ENTITY><br/>
<CURRENCY>Afghani</CURRENCY><br/>
<ALPHABETIC_CODE>AFN</ALPHABETIC_CODE><br/>
<NUMERIC_CODE>971</NUMERIC_CODE><br/>
<MINOR_UNIT>2</MINOR_UNIT><br/>
</ISO_CURRENCY><br/>
<ISO_CURRENCY><br/>
<ENTITY>ÃLAND ISLANDS</ENTITY><br/>
<CURRENCY>Euro</CURRENCY><br/>
<ALPHABETIC_CODE>EUR</ALPHABETIC_CODE><br/>
<NUMERIC_CODE>978</NUMERIC_CODE><br/>
<MINOR_UNIT>2</MINOR_UNIT><br/>
</ISO_CURRENCY><br/>
</ISO_CCY_CODES>

<br/>
I could transform it into an annonymous type collection with following code:<br/>
<div id="x_code
<h4>CODE</h4>
Dim ISOxml As XElement = XElement.Load("D:VB2010Projectscon_ISOcodes_ch14Currency ISO Codes.xml")<br/>
<br/>
Put ISO codes into a collection of anonymous types<br/>
Dim iCodes = _<br/>
From code In ISOxml.Descendants("ISO_CURRENCY")<br/>
Select New With {.Country = code.Elements("ENTITY").Value,<br/>
.Name = code.Elements("CURRENCY").Value,<br/>
.ISOcode = code.Elements("ALPHABETIC_CODE").Value,<br/>
.NUMcode = code.Elements("NUMERIC_CODE").Value}<br/>
For Each code In iCodes<br/>
Debug.WriteLine(code.Country & vbTab & code.Name & vbTab & code.ISOcode)<br/>
Next

<br/>
the resulting output:
<div id="x_code
<h4>CODE</h4>
AFGHANISTAN Afghani AFN<br/>
ÃLAND ISLANDS Euro EUR

<br/>
However, I would like to Type the collection, thefore I defined a class CurrencyCode as follows:
<div id="x_code
<h4>CODE</h4>
Public Class CurrencyCode<br/>
Public Property Country As String<br/>
Public Property Name As String<br/>
Public Property ISOcode As String<br/>
Public Property NUMcode As String<br/>
End Class

Then I tried to proceed. After much experimenting, I finally managed to get an error free statement:<br/>
<div id="x_code
<h4>CODE</h4>
Put ISOcodes into a collection of CurrencyCode Type<br/>
CurrencyCode must be defined as a class<br/>
Dim iiCodes As CurrencyCode = _<br/>
CType((From code In ISOxml.Descendants("ISO_CURRENCY")<br/>
Select New CurrencyCode With {.Country = code.Elements("ENTITY").Value,<br/>
.ISOcode = code.Elements("ALPHABETIC_CODE").Value,<br/>
.NUMcode = code.Elements("NUMERIC_CODE").Value}), CurrencyCode)

which ... flunked at run time with following execption:<br/>
<div id="x_code
<h4>CODE</h4>
Cannot convert an object of type WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,con_ISOcodes_ch14.CurrencyCode] into type con_ISOcodes_ch14.CurrencyCode.

<br/>
How could I achieve my goal?<br/>
Ideally I would like to have a declaration as a typed list:<br/>
<div id="x_code
<h4>CODE</h4>
Dim iiiCodes() as CurrencyCode = ...

but this seems even farther away

View the full article
 
Back
Top