[英]Scala XML Match nodes using Attributes
I am loading a XML file in scala which looks like this: 我正在Scala中加载一个XML文件,如下所示:
<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 . 如果您在Scala中使用xml做很多工作,那么我建议您使用Anti-XML 。 It gives you a lot better syntax and performance improvements (for the most part) over scala's native xml handling.
与scala的本机xml处理相比,它在大多数情况下为您提供了更好的语法和性能改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.