使用Scala,如何将具有元素的XML元素区分为子元素或具有文本?

时间:2009-11-13 21:11:24

标签: xml parsing scala

我正在解析一些xml,给定一个特定的节点,我试图找出它们中的哪一个:

  • 具有嵌套元素的元素

    < theElement>< nestedElement> foobar的< / nestedElement>< / theElement>

  • 包含文字/数据的元素

    < theElement> foobar的< / theElement>

我已经尝试检查Node.text的长度,但Node.text在上述两个示例中都为 theElement 返回“foobar”。

我的代码通过XML结构递归,并且每个点都需要知道它是否到达某些文本/数据,或者下面是否有更多元素。

2 个答案:

答案 0 :(得分:5)

def textChildren(xml: Node) = xml match {
  case Elem(prefix, label, attribs, scope, Text(text)) => println("Only text children: "+text)
  case _ => println("Other kinds of children")
}

scala> textChildren(<a>XML example</a>)
Only text children: XML example

scala> textChildren(<a><nested>XML example</nested></a>)
Other kinds of children

scala> textChildren(<a>Text with <nested>XML</nested> example</a>)
Other kinds of children

答案 1 :(得分:0)

也许这是解决方案,在repl中尝试过:

scala> val xml1 = <theElement><nestedElement>foobar</nestedElement></theElement>
xml1: scala.xml.Elem = <theElement><nestedElement>foobar</nestedElement></theElement>

scala> val xml2 = <theElement>foobar</theElement>
xml2: scala.xml.Elem = <theElement>foobar</theElement>

scala> xml1.child.first.label
res0: String = nestedElement

scala> xml2.child.first.label
res1: String = #PCDATA

e.g。

if ( node.child.first.label == "#PCDATA" ) {
  // Its got data in it
} else {
  // Its got elements below it
}