0

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

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 文档作为输出而不重复?

4)有没有一种通用的方法来转换 xml 树以获取具有名称和 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]])
                        }
                    }
                }
4

1 回答 1

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>
于 2013-02-27T15:06:22.013 回答