I am loading a XML file in scala which looks like this:
<dataset>
<item label="neutral" target="general" tweetid="936466790" username="B_E_X">
<content>Jim Lehrer just directed the debate audience ... 30 seconds ... #tweetdebate</content>
</item>
<item label="neutral" target="general" tweetid="936466992" username="Jonathan Fields">
<content>Here we go. #tweetdebate</content>
</item>
</dataset>
Now, I am trying to get the labels of each of the items using attributes, but it always returns me none? I tried several ways like matching, parsing etc.:
val rawXML = XML.loadFile(file).toList
rawXML.foreach(x => println(x.attribute("label")))
I also tried matching as follows:
myXML match {
case <dataset>
{item @ <item>{theText}</item>}
</dataset> =>
println("An %s text: %s".format(item \ "@label", theText))
There are a few ways to do this. The problem with your first version is that you're not searching the child nodes for "label":
//Note the three whitespace nodes
scala> rawXML.child.foreach(x => println(x.attribute("label")))
None
Some(neutral)
None
Some(neutral)
None
You can do a more refined search of all children nodes for "item"s with "label" attributes:
scala> rawXML \ "item" \\ "@label"
res0: scala.xml.NodeSeq = NodeSeq(neutral, neutral)
If you're doing a lot work with xml in scala then I would recommend using Anti-XML . It gives you a lot better syntax and performance improvements (for the most part) over scala's native xml handling.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.