通用 XML 可以像 Groovy 中的简单 XML 一样解析吗?
给定一个漂亮、简单的 XML 结构,XmlSlurper() 可以让我非常轻松地从中读取值。
def xml = "<html><head><title>groovy</title></head></html>"
def html = new XmlSlurper().parseText(xml)
println html.head.title
有没有一种方法可以使这种简单的树导航对于通用(基于类型等)XML 成为可能。 理想情况下,在下面的代码片段中,我想通过值的 name 属性来遍历这些值,但相反,我必须执行所有这些搜索:
def genxml = """
<doc>
<lst name = "head">
<str name = "title">groovy</str>
<str name = "keywords">java xml</str>
</lst>
</doc>"""
def doc = new XmlSlurper().parseText(genxml)
println doc.lst.find { it.@name == "head" }.str.find { it.@name == "title" }
有没有一种方法可以像这样遍历这些值:
println doc.head.title
Given a nice, simple XML structure, XmlSlurper() can allow me to read values from it very easily.
def xml = "<html><head><title>groovy</title></head></html>"
def html = new XmlSlurper().parseText(xml)
println html.head.title
Is there a way to make this simple tree navigation possible for generic (type-based, etc) XML. Ideally, in the snippet of code below, I'd like to walk the values by their name attribute, but instead, I have to do all this searching:
def genxml = """
<doc>
<lst name = "head">
<str name = "title">groovy</str>
<str name = "keywords">java xml</str>
</lst>
</doc>"""
def doc = new XmlSlurper().parseText(genxml)
println doc.lst.find { it.@name == "head" }.str.find { it.@name == "title" }
Is there a way to walk this just as:
println doc.head.title
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
head 和 title 是属性。
slurper 和解析器之间存在一些非常微妙的差异: http://www. ibm.com/developerworks/java/library/j-pg05199/
您可以执行此操作:
但请查看输出:
head and title are attributes.
there are some really subtle differences between slurper and parser: http://www.ibm.com/developerworks/java/library/j-pg05199/
you can do this:
but look at the output: