给定给定节点的 id 和路径图,我构建一个 xml 树:
def trees = [:]
trees.put(1,"TEST/folder1")
trees.put(2,"TEST/folder2")
trees.put(3,"TEST/folder1/folder1.1")
trees.put(4,"TEST/folder2/folder2.1/folder2.1.2")
trees.put(5,"TEST/folder1/folder1.2")
trees.put(6,"TEST/folder1/folder1.2/folder1.2.1/")
trees.put(7,"TEST/folder1/folder1.2/folder1.2.2/")
trees.put(8,"TEST/folder1/folder1.2/folder1.2.2/1.2.2.1")
sw = new StringWriter()
def rslt = { [:].withDefault{ owner.call() } }().with { t ->
trees.each { k, v ->
v.tokenize( '/' ).inject( t ) { tr, i -> tr[ i ] }
}
return t
}
new groovy.xml.MarkupBuilder(sw).with {
visitor = { k, v -> "$k" { v instanceof Map ? v.collect(visitor) : mkp.yield(v) } }
ROOT { rslt.collect visitor }
}
println sw.toString()
最后得到这个输出:
<TEST>
<folder1>
<folder1.1 />
<folder1.2>
<folder1.2.1 />
<folder1.2.2>
<1.2.2.1 />
</folder1.2.2>
</folder1.2>
</folder1>
<folder2>
<folder2.1>
<folder2.1.2 />
</folder2.1>
</folder2>
</TEST>
</ROOT>
有没有一种常规的方法来添加从初始树图值继承的属性 id、名称、父深度、url?
格式良好的 xml 文档示例:
<folder2 name="folder2" id="2" parent="TEST" depth="1" url="TEST/folder2">
<folder2.1.1 name="folder2.1.1" id="2" parent="TEST" depth="2" url="TEST/folder2">
<folder2.1.1.1 name="folder2.1.1.1" id="3" parent="TEST" depth="3" url="TEST/folder2"/>
</folder2.1.1>
</folder2>
有什么想法或建议吗?
干杯