Skip to content

Instantly share code, notes, and snippets.

@mujahidk
Last active September 14, 2017 14:46
Show Gist options
  • Select an option

  • Save mujahidk/a4692fc4528217d1612ebb6412c00158 to your computer and use it in GitHub Desktop.

Select an option

Save mujahidk/a4692fc4528217d1612ebb6412c00158 to your computer and use it in GitHub Desktop.
Print xml node names in basic XPath format.
class NodePrinter{
private String filePath
private String namespacePrefix
NodePrinter(String filePath, String namespacePrefix){
this.filePath = filePath
this.namespacePrefix = namespacePrefix
}
def printTree(){
def rootNode = new XmlParser().parse(new File(this.filePath))
this.printNode(rootNode, "/")
}
def skipNode(def node){
node.children().size() > 1
}
def printNode(def node, String path){
String fullPath = "${path}/${node.name()}".replace(namespacePrefix, "")
if(!skipNode(node)){
println fullPath
}
node.children().each {
if(it instanceof groovy.util.Node){
printNode(it, fullPath)
} else if(it instanceof java.lang.String) {
// Ignore text node
} else {
println "Unknown node: " + it.getClass()
}
}
}
}
// Run
def path = "xml-file-path.xml"
new NodePrinter(path, "ns:").printTree()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment