开发者

Finding XML elements that dont have subelements or value in scala

Consider the following XML :

开发者_如何学Python
val someXML =
<sammich>
  <bread>wheat</bread>
  <meat>salami</meat>
  <extras></extras>
  <condiments>
    <condiment expired="true">mayo</condiment>
    <condiment expired="false">mustard</condiment>
  </condiments>
</sammich>

I want to find out which element does not have subelements, like for example in the above XML that element would be extras. The length method of NodeSeq returns 1 for extras and isEmpty returns false. So, how can we test for such elements which dont have any sub elements or value ?

Please Help Thanks


Nodes are lists of length 1 containing themselves. Children can be retrieved with descendant If you ask

someXML.descendant(7).descendant.length

you'll get a 0 (in your example, <extras></extras> is at position 7 (since newlines+whitespace count as text objects). You may or may not also wish to count attributes:

someXML.descendant(7).attributes.length


I'll just add a bit to Rex's answer. Note that the descendant method includes comments and processing instructions. Assuming you only want to count sub-elements and text nodes, you'll have to do a bit more work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜