Can we do this snippet?
Are there any improvements when I can improve this code? Perhaps there are some groovy language features? This snippet aligns the xml file: node / node / node
def root = new XmlParser().parse("src/your_xml.xml")
root.depthFirst().each { n ->
def name = n.name()
while(n?.parent()){
name = "${n?.parent()?.name()}/${name}";
n = n?.parent()
}
println name
}
+2
source to share
2 answers
I could refactor the code to use a more functional style.
def x = """
<test>
<test1>
<test2/>
</test1>
<test2>
<test3/>
<test4>
<test5/>
</test4>
</test2>
</test>
""".trim()
def root = new XmlParser().parseText(x)
def nodePath(node) {
node.parent() ? "${nodePath(node.parent())}/${node.name()}" : node.name()
}
root.depthFirst().each {
println nodePath(it)
}
assert nodePath(root.test2[0].test4[0].test5[0]) == "test/test2/test4/test5"
+2
source to share