2

I'm very very new to scala so bear with me if this seems basic. I have the following XML file

<xml>
    <things/>
    <items>

        <stuff name="John"/>
        <stuff name="Jacob"/>
        <stuff name="George"/>
        <stuff name="alice"/>

    </items>    

</xml>

and from this file I want to see if a specific name attribute is present in a stuff tag. (ex: see if Jacob exists or see if Lisa exists within the xml file)

So far I have the following code

import scala.xml._
val xml = XML.loadFile("sample.xml")
val stuff = (xml \\ "stuff")
//The following val contains: scala.collection.immutable.Seq[scala.xml.MetaData] = List( name="John",  name="Jacob",  name="George",  name="alice")
val names= stuff.map(_.attributes)

Now I notice that this creates a List but when I use the contains method on the val names it gives me false even for a value like alice.

val exists= names.contains("alice")

produces this output in the REPL:

exists: Boolean = false

How would I test if a value is contained in this file?

1 Answer 1

3

The type for names is a Seq[scala.xml.MetaData] and you are using contains to search for the String "alice" which as you can see isn't going to work.

To get the text from the name attribute map each scala.xml.MetaData to it's text representation with text and you get back a Seq[String] which allows you to search for "alice".

scala> val names = (xml \\ "items" \\ "stuff" \\ "@name").map(_.text)
names: scala.collection.immutable.Seq[String] = List(John, Jacob, George, alice)

scala> names.contains("alice")
res22: Boolean = true
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was stuck on this for hours yesterday

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.