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

Ale*_*ack 1 xml parsing scala

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

  • 具有嵌套元素的元素

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

  • 包含文本/数据的元素

    <theElement> foobar的</ theElement>

我已经试过检查Node.text的长度,但Node.text返回"foobar的"为theElement在以上两个例子.

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

Dan*_*ral 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
Run Code Online (Sandbox Code Playgroud)