views:

105

answers:

2

Hey,

are there any improvements where i can improve this code? Maybe there are some groovy language features? This snippet flattens a xml file to: 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
}
+1  A: 

-- Edit: Ignore me, I'm wrong [see comments] (not the last line though);

I suspect you can write (but I could be wrong, I have no experience with this language)

while(n = n?.parent()){

But honestly; don't go with something that is cool, go with something that is readable.

Noon Silk
+1 on the "don't go with something cool, go with something readable"
quip
You're definitely right. I am also for readable code! Maybe you just get me wrong, i searched for some groovy features i can use. that maybe makes this code more readable. Thanks :)
codedevour
For your code: This isn't possible, only with an do while, buts that not a feature in groovy afaik
codedevour
+2  A: 

I might 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"
John Wagenleitner