redeagle47
redeagle47

Reputation: 1377

Scala XML can't find attribute

I am trying to parse an XML attribute from the following XML:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

Specifically, I want to get the name attribute from the country tag. I am using this code:

import scala.xml.XML

object XmlReader {
    def main(args: Array[String]) {
        val xml = XML.loadFile("src/main/resources/country_data.xml")
        println(xml \\ "data" \\ "country" \ "@name")
    }
}

No matter what I try, I get an empty value. I know the "xml \ 'data' \ 'country'" is good because I can see XML printed out when I run it. But as soon as I try to get the attribute of the country tag, I get nothing. It looks like I'm doing exactly what this tutorial shows (http://alvinalexander.com/scala/scala-xml-searching-xmlns-namespaces-xpath-parsing) but I'm not getting a result.

Update: When I only have one country node, the following works:

(xml \\ "data" \ "country" \ "@name").text

I have no idea why.

Upvotes: 0

Views: 185

Answers (1)

choroba
choroba

Reputation: 242343

If there's more than one hit for the search, you get a nodelist back. You can iterate it with a loop:

val xml = <r><p><c a="first"/><c a="second"/></p></r>
for ( c <- xml \\ "r" \\ "p" \\ "c") {
    println(c \\ "@a")
}   

Upvotes: 1

Related Questions