这就是代码的样子
import scala.xml.{Elem, Node, PCData}
import scala.xml.transform.{RewriteRule, RuleTransformer}
val doc: Elem = <data>
<level1>
<Weekly>
<Properties>
<Property key="Sun"/>
<Property key="Mon"/>
<Property key="Tue"/>
</Properties>
</Weekly>
</level1>
<level2>
<Monthly>
<Properties>
<Property key="Jan"/>
<Property key="Feb"/>
<Property key="Mar"/>
</Properties>
</Monthly>
</level2>
</data>
final class traverseRule extends RewriteRule {
override def transform(ns: Seq[Node]): Seq[Node] = ns match {
case n: Node => println(n.label)
n
}
}
new RuleTransformer(new traverseRule()).transform(doc).head
我得到的是
#PCDATA
#PCDATA
#PCDATA
#PCDATA
Property
#PCDATA
Property
#PCDATA
Property
#PCDATA
Properties
#PCDATA
Weekly
#PCDATA
level1
#PCDATA
#PCDATA
#PCDATA
#PCDATA
Property
#PCDATA
Property
#PCDATA
Property
#PCDATA
Properties
#PCDATA
Monthly
#PCDATA
level2
#PCDATA
data
所需吗
我需要元素data
,level
,Weekly
而不是#PCDATA
。我怎样才能做到这一点?
由于
答案 0 :(得分:0)
如果您要列出XML文档中的所有元素,则以下函数将起作用。
import scala.xml.{Elem, Node, PCData}
val doc: Elem = <data>
<level1>
<Weekly>
<Properties>
<Property key="Sun"/>
<Property key="Mon"/>
<Property key="Tue"/>
</Properties>
</Weekly>
</level1>
<level2>
<Monthly>
<Properties>
<Property key="Jan"/>
<Property key="Feb"/>
<Property key="Mar"/>
</Properties>
</Monthly>
</level2>
</data>
def listNodes(elem: scala.xml.Elem): Seq[scala.xml.Elem] = {
elem.child flatMap {
case x: scala.xml.Elem => x +: listNodes(x)
case _ => Nil
}
}
val elements = doc +: listNodes(doc)
scala> elements.map(_.label)
res0: Seq[String] = ArrayBuffer(data, level1, Weekly, Properties, Property, Property, Property, level2, Monthly, Properties, Property, Property, Property)
元素是Scala元素的序列,其中包含文档中的所有元素标记。函数listNodes
函数以递归方式查找XML节点中的所有元素节点。