在 scala 中查找没有子元素或值的 XML 元素
考虑以下 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>
我想找出哪个元素没有子元素,例如在上面的 XML 中,该元素为 extras。 NodeSeq 的 length 方法对于 extras 返回 1,isEmpty 返回 false。那么,我们如何测试这些没有任何子元素或值的元素呢?
请帮忙 谢谢
Consider the following 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>
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
节点是长度为 1 且包含自身的列表。可以使用
descendant
检索子项,如果您询问,您将得到 0(在您的示例中, 位于位置 7(因为换行符) +空格也算作文本对象)。您可能也可能不希望计算属性:
Nodes are lists of length 1 containing themselves. Children can be retrieved with
descendant
If you askyou'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:我将在雷克斯的回答中添加一些内容。请注意,
descendant
方法包含注释和处理指令。假设您只想计算子元素和文本节点,则需要做更多的工作: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: