Android Question Xml2Map Error while parsing RSS

Pendrush

Well-Known Member
Licensed User
Longtime User
When I try to parse attached text.xml (RSS) I'm getting error:
java.lang.ClassCastException: anywheresoftware.b4a.objects.collections.Map$MyMap cannot be cast to java.util.List
on line
B4X:
For Each item As Map In items
I have tested XML against various online validators everyone say it's a valid XML.
Anyone know what's wrong here?
 

Attachments

  • test.xml
    541 bytes · Views: 253

Pendrush

Well-Known Member
Licensed User
Longtime User
I have found what is problem, If XML contain only one ITEM tag, then error is triggered. In this attached file there is two ITEM tags and parser work as expected.
Now the question is how to parse XML with only one ITEM tag inside.
 

Attachments

  • test 2.xml
    709 bytes · Views: 225
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
did you check the generated map?

B4X:
    If FirstTime Then
        Dim xm As Xml2Map
    xm.Initialize
    ParsedData = xm.Parse(File.ReadString(File.DirAssets, "rss.xml"))
    End If
    Log(ParsedData)
    For Each key As String In ParsedData.Keys
        Log(ParsedData.Get(key))       
    Next

Ther content of the only key in the map is
{Attributes={version=2.0}, channel={title=1, link=2, description=3, language=4, pubDate=Mon, 16 Jan 2017 12:55:01 +0100, lastBuildDate=Mon, 16 Jan 2017 12:55:01 +0100, docs=http://www.example.com, webMaster=[email protected], item={link=http://www.example.com, title=Test, description=test desc, pubDate=Mon, 16 Jan 2017 12:55:01 +0100}}}
 
Upvote 0

Pendrush

Well-Known Member
Licensed User
Longtime User
Yes, but this code trigger error:
B4X:
Dim rss As Map = ParsedData.Get("rss")
Dim channel As Map = rss.Get("channel")
Dim items As List = channel.Get("item")

For Each item As Map In items '<--- error (java.lang.ClassCastException: anywheresoftware.b4a.objects.collections.Map$MyMap cannot be cast to java.util.List)
Next
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
SS-2017-01-17_08.50.14.png


Xml2Map works properly here.
If there is a single element then it will return a Map. If there are multiple elements with the same name then it will return a List (the other option is to always return a List for all items).

In this case you need to add a check:
B4X:
if channel.Get("item") Is Map Then
 'single item
 Dim item As Map = channel.Get("item")
Else
 Dim items As List = channel.Get("item")
 For Each item As Map In items
  ...
 
Upvote 0

Similar Threads

Top