解析字符串映射并转换为xml

时间:2013-02-27 14:44:47

标签: xml groovy

给出id和字符串路径的映射,我需要解析并构建一个xml doc。

1)以下是带有ID的路径地图(从数据库中收集):

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")       

2)关闭定义

def parseTreeNodes(HashMap<Integer,String> t) {
    def treeNodes = [:]
    def nodeItems = []
    def subItems=[]
    t.each { k,v ->
        subItems = v.split('/')
        subItems.eachWithIndex { node,i ->
            if(!treeNodes.values().contains(node)) {
                treeNodes.put(id:k,[depth:i,node:node,parent:subItems[i-1]])
            }
        }
    }
    println treeNodes.toString() + "---"
}

3)调用闭包

parseTreeNodes(trees)

如何将xml转换应用于此过滤器,以便将xml doc作为输出而不是重复?

4)是否有一种常规的方法来转换xml树以获取具有name和id的属性(从第一次迭代中提取)???

<folder name="folder1" id="1" depth="1">
      <folder name="folder1.2" id="2" path="folder1/folder1.2" depth="2"/>
 <folder> 
...

事实上,以下地图已经包含了所有数据:

def treeNodes = [:]
     trees.each { k,v ->
                    subItems = v.split('/')
                    subItems.eachWithIndex { node,i ->
                        if(!treeNodes.values().contains(node)) {
                            treeNodes.put(id:k,[depth:i,node:node,parent:subItems[i-1]])
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作来生成文件夹地图:

// Build a map of folders (see https://gist.github.com/kiy0taka/2478499)
def rslt = { [:].withDefault{ owner.call() } }().with { t ->
  trees.each { k, v ->
    v.tokenize( '/' ).inject( t ) { tr, i -> tr[ i ] }
  }
  t
}

然后将这样的地图转换为xml

// Taken from https://gist.github.com/uehaj/875631
sw = new StringWriter()
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()

打印:

<root>
  <TEST>
    <folder1>
      <folder1.1 />
      <folder1.2>
        <folder1.2.2>
          <1.2.2.1 />
        </folder1.2.2>
      </folder1.2>
    </folder1>
    <folder2>
      <folder2.1>
        <folder2.1.2 />
      </folder2.1>
    </folder2>
  </TEST>
</root>