查找scala中没有子元素或值的XML元素

查找scala中没有子元素或值的XML元素,xml,scala,Xml,Scala,考虑以下XML: val someXML = <sammich> <bread>wheat</bread> <meat>salami</meat> <extras></extras> <condiments> <condiment expired="true">mayo</condiment> <condiment expired="fal

考虑以下XML:

val someXML =
<sammich>
  <bread>wheat</bread>
  <meat>salami</meat>
  <extras></extras>
  <condiments>
    <condiment expired="true">mayo</condiment>
    <condiment expired="false">mustard</condiment>
  </condiments>
</sammich>
val-someXML=
小麦
意大利腊肠
梅奥
芥末
我想找出哪个元素没有子元素,例如在上面的XML中,该元素将是extras。NodeSeq的length方法为extra返回1,isEmpty返回false。那么,我们如何测试这些没有任何子元素或值的元素呢

请帮忙
感谢

节点是包含自身的长度为1的列表。如果需要,可以使用
子代
检索子代

someXML.descendant(7).descendant.length
您将得到一个0(在您的示例中,
位于位置7(因为换行符+空格作为文本对象计数)。您可能希望也可能不希望计数属性:

someXML.descendant(7).attributes.length

我只想在Rex的回答中添加一点内容。请注意,
子代
方法包含注释和处理说明。假设您只想计算子元素和文本节点,您需要做更多的工作:

def isNodeEmpty(n: Node) = 
   n.descendant collect { case c @ (_: Text | _: Elem) => c } isEmpty