树在groovy排序

时间:2013-03-02 17:44:37

标签: xml groovy

给一个LinkedHashMap,我正在尝试在groovy中构建一个完整的xml树。

1)地图:

def trees = [:]
trees.put(1,[id:'1',path:'ROOT/folder1',name:'folder1',isFolder:'true'])
trees.put(2,[id:'2',path:'ROOT/folder1/folder1.1',name:'folder1.1',isFolder:'true'])
trees.put(3,[id:'3',path:'ROOT/folder1/folder1.1/folder1.1.1',name:'folder1.1.1',isFolder:'true'])
trees.put(4,[id:'4',path:'ROOT/folder2',name:'folder2',isFolder:'true'])
trees.put(5,[id:'5',path:'ROOT/folder3',name:'folder3',isFolder:'true'])
trees.put(6,[id:'6',path:'ROOT/folder3/folder3.1',name:'folder3.1',isFolder:'true'])

2)排序树关闭:

//def rslt = { [:].withDefault{ owner.call() } }
def a = []
def rslt = { [:].withDefault{ owner.call() } }().with { t ->
  trees.each { k, v ->
    v.path.tokenize( '/' ).inject( t ) { tr, i -> tr[ i ] }
  }
  return t
}

3)如何使用xml slurper构建一个Xml文档,

模型会是这样的:

<ROOT>
<folder1 name="folder1" id="1" parent="ROOT" depth="1" path="ROOT/folder1">
      <folder1.1 name="folder1.1" id="2" parent="folder1" depth="2" path="ROOT/folder1/folder1.1">
           <folder1.1.1 name="folder1.1.1" id="3" parent="folder1.1" depth="3" path="ROOT/folder1.1/folder1.1.1"/>
       </folder1.1>
</folder1>
...
</ROOT>

使用像groovy.xml.MarkupBuilder(sw).with {

这样的sthg寻找闭包

有任何想法或建议吗?

BR。

1 个答案:

答案 0 :(得分:0)

您可以通过递归遍历节点映射来使用groovy.xml.StreamingMarkupBuilder构建XML。您在第二步中创建的地图会丢失trees中定义的所有属性。要保留它们,您必须首先更改该部分:

// An empty map. Default value for nonexistent elements is an empty map.
def struc = {[:].withDefault{owner.call()}}()

trees.each { key, val ->
    // iterate through the tokenized path and create missing elements along the way
    def substruc = struc
    val.path.tokenize('/').each {
        // if substruc.nodes does not exist it will be created as an empty map
        // if substruc.nodes[it] does not exist it will be created as an empty map
        substruc = substruc.nodes[it]
    }
    // assign the attributes to the map in .attr
    val.each{ attrKey, attrVal ->
        substruc.attr[attrKey] = attrVal
    }
}

这将产生如下地图:

[nodes: [ROOT: [nodes: [folder1: [attr: [id:1, ...], nodes: [...]]]]]

将在StreamingMarkupBuilder中使用的闭包将使用另一个闭包以递归方式迭代struc中的节点,同时将.attr指定为节点的属性,并将.nodes指定为// we will use this builder to create our XML def builder = new groovy.xml.StreamingMarkupBuilder() builder.encoding = "UTF-8" // closure for our xml structure def xml = { // closure to be recursively called for each element in the nodes maps def xmlEach xmlEach = { key, val -> out << { "${key}"(val.attr) { val.nodes.each(xmlEach) } } } struc.nodes.each(xmlEachClosure) } println builder.bind(xml) 节点的子节点。

<ROOT>
    <folder1 id='1' path='ROOT/folder1' name='folder1' isFolder='true'>
        <folder1.1 id='2' path='ROOT/folder1/folder1.1' name='folder1.1' isFolder='true'>
            <folder1.1.1 id='3' path='ROOT/folder1/folder1.1/folder1.1.1' name='folder1.1.1' isFolder='true'></folder1.1.1>
        </folder1.1>
    </folder1>
...
</ROOT>

作为输出,您可以获得以下XML格式:

{{1}}