动态创建xml节点

时间:2013-08-08 19:20:12

标签: xml groovy nodes

我有一个特殊的需要,我正在解析一个文件,然后我需要根据我解析的数据创建一个xml文件。

例如,我创建了两个地图(tableMap,fieldMap)。

tableMap: [1:{Table=patient}, 2:{Table=provider}]
fieldMap: [1:{Table=patient, Field=id}, 2:{Table=patient, Field=gender},  
   3:{Table=provider, Field=id}, 4:{Table=provider, Field=name}]

使用Groovy我将从tableMap开始循环并获取第一个Table(患者)。然后我将遍历fieldMap以获取与Table匹配的字段。

下面是一些示例代码,演示了如何使用“value.Table(tag:'01',value.Field)”动态创建节点和元素名称“:

tableMap.each
{ tKey, tValue ->

    // Find the Table value in the fieldMap that matches the value 
    // in the tableMap      
    def tableFields = fieldMap.findAll { fKey, fValue -> 
        fValue.Table == tValue.Table 
    }
    tValue.Table = []

    // Create an XML file with all the tables and field names collected.
    xsdToXml.root() 
    {

        // dynamically create xml nodes
        tableFields.each 
        { key, value ->
            value.Table + '()' {
                value.Table(tag:'01',value.Field)       
            }
        }
    }
}

我不确定这是否可能,如果不是,我只是想让别人告诉我,所以我不再浪费时间了。如果是的话,我会很感激如何做到这一点。

谢谢 - 卡尔

1 个答案:

答案 0 :(得分:3)

是的,你没有说出你希望输出XML看起来像什么,而是采用fieldMap(你不需要tableMap):

def fieldMap = [ 1:[ Table:'patient', Field:'id' ], 
                 2:[ Table:'patient', Field:'gender' ],  
                 3:[ Table:'provider', Field:'id' ],
                 4:[ Table:'provider', Field:'name' ] ]

你可以这样做:

import groovy.xml.*

String x = new StreamingMarkupBuilder().bind {
    xml {
        fieldMap.values().groupBy { it.Table }.each { table, values ->
            "${table}" {
                values.each {
                    "${it.Field}"()
                }
            }
        }
    }
}

生成xml:

<xml>
    <patient>
        <id/>
        <gender/>
    </patient>
    <provider>
        <id/>
        <name/>
    </provider>
</xml>
相关问题