使用 Scala 解析 XML:相当于“getElementByTagName(name)”在JS中
Scala 中的 XML 解析似乎并不像应有的那么简单和直接。
我需要的是行为类似于 JavaScript 中的 document.getElementsByTagName(name) 的东西,但出于我的目的,我需要的只是特定标记名称的第一个元素。这就是我最终得到的结果:
import scala.xml.{Document, Elem, Node}
import scala.xml.parsing.ConstructingParser
def _getFirstMatchingElementByName(search: String, n: Node): Option[Node] = {
if (n.label == search) {
Some(n)
} else {
var i = 0
var result: Option[Node] = None
try {
while (result == None) {
result = _getFirstMatchingElementByName(search, n.child(i))
i += 1
}
} catch {
case e: IndexOutOfBoundsException => None
}
result
}
}
它基本上会递归,直到找到匹配项或用尽所有可能性。
现在要求我具备这种能力的功能已经发布了,我对此进行了更多的审查,这确实让我感到困扰。我确信有许多 Java 库可用于帮助解析 XML,但考虑到 Scala 对生成 XML 的本机支持(即它几乎可以在任何地方内联),我很好奇我是否遗漏了某些内容。
在 Scala 中是否有更好的方法来做到这一点?
XML parsing in Scala doesn't seem to be as easy and straightforward as it should be.
What I needed was something that behaved similar to document.getElementsByTagName(name) in JavaScript, but for my purposes all I needed was the first element of a particular tag-name. Here is what I ended up with:
import scala.xml.{Document, Elem, Node}
import scala.xml.parsing.ConstructingParser
def _getFirstMatchingElementByName(search: String, n: Node): Option[Node] = {
if (n.label == search) {
Some(n)
} else {
var i = 0
var result: Option[Node] = None
try {
while (result == None) {
result = _getFirstMatchingElementByName(search, n.child(i))
i += 1
}
} catch {
case e: IndexOutOfBoundsException => None
}
result
}
}
It basically recurses through until a match is found or all possibilities are exhausted.
Now that the feature which required that I have this ability has been released I have reviewed this a little more and it really bugs me. I'm sure there are many Java libraries available to help parse XML, but given the native support that Scala has for generating XML (i.e. it can pretty much just be inlined anywhere), I am curious if I am missing something.
Is there a better way to do this in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你做错了!
我所需要的只是特定标记名称的第一个元素
给定这个 xml:
现在调用此代码将为您提供具有给定标签名称的所有节点的列表:
仅获取第一个:
PS deep-first 元素将被视为头。
You doing it wrong!
all I needed was the first element of a particular tag-name
given this xml:
Now calling this code will give you list of all nodes with given tag name:
To get only first one:
P.S. deep-first element would be treated as head.