Given a nice, simple XML structure, XmlSlurper() can allow me to read values from it very easily.
对于一个简单的XML结构,XmlSlurper()可以很容易地从它读取值。
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:
是否有一种方法可以使这个简单的树导航成为通用的(基于类型的)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" }
Is there a way to walk this just as:
有没有一种方法可以做到:
println doc.head.title
1 个解决方案
#1
0
head and title are attributes.
标题和标题是属性。
there are some really subtle differences between slurper and parser: http://www.ibm.com/developerworks/java/library/j-pg05199/
slurper和解析器之间有一些非常细微的区别:http://www.ibm.com/developerworks/java/library/j-pg05199/
you can do this:
你可以这样做:
println "${doc.lst.str[0]} ${doc.lst.str[0].@name}"
println doc.lst.str.each {
println "${it} ${it.@name}"
}
but look at the output:
但是看看输出:
groovy title
groovy title
java xml keywords
groovyjava xml
#1
0
head and title are attributes.
标题和标题是属性。
there are some really subtle differences between slurper and parser: http://www.ibm.com/developerworks/java/library/j-pg05199/
slurper和解析器之间有一些非常细微的区别:http://www.ibm.com/developerworks/java/library/j-pg05199/
you can do this:
你可以这样做:
println "${doc.lst.str[0]} ${doc.lst.str[0].@name}"
println doc.lst.str.each {
println "${it} ${it.@name}"
}
but look at the output:
但是看看输出:
groovy title
groovy title
java xml keywords
groovyjava xml