我有树状结构
class FSNode {
FSEntity data
def parent
def children = []
boolean isRoot() {
parent == null
}
}
我像这样实例化
// create filesystem folder
def fsEntityDirectory = new FSEntity(name: 'folder')
def fsDirectoryNode = new FSNode(parent: null, data: fsEntityDirectory)
def fsEntityDirectory2 = new FSEntity(name: 'folder1')
def fsDirectoryNode2 = new FSNode(parent: fsDirectoryNode, data: fsEntityDirectory2)
// create filesystem file
def fsEntity = new FSEntity(name: 'basic.txt', size: 10) // file system entity
def fsEntityNode = new FSNode(data: fsEntity, parent: fsDirectoryNode)
def fsEntity2 = new FSEntity(name: 'file.png', size: 12)
def fsEntityNode2 = new FSNode(data: fsEntity2, parent: fsDirectoryNode2)
fsDirectoryNode2.children << fsEntityNode2
fsDirectoryNode.children << fsDirectoryNode2
fsDirectoryNode.children << fsEntityNode
最后我想得到这样的东西
<filesystem-root>
<directory name="folder">
<directory name="folder1">
<file name="file.png" size="12" />
</directory>
<file name="basic.txt" size="10" />
</directory>
</filesystem-root>
这是我序列化的方式
static def serializeFS(node, output, xml = new MarkupBuilder(output)) {
if (node.children) {
xml.directory(name: node.data.name)
node.children.each {
xml = serializeFS(it, output, xml)
}
} else {
node.data.size ?
xml.file(name: node.data.name, size: node.data.size) :
xml.directory(name: node.data.name, "")
}
xml
}
static def wrapFS(output, xml) {
xml."filesystem-root"(output)
}
但最终我得到了
<directory name='folder' />
<directory name='folder1' />
<file name='file.png' size='12' />
<file name='basic.txt' size='10' />
有什么问题?
答案 0 :(得分:2)
您可以尝试以下方式:
def serializeFSNode(FSNode node, MarkupBuilder m) {
if(node.children) {
m.directory(name: node.data.name) {
node.children.each { child ->
serializeFSNode(child, m)
}
}
}
else {
m."${node.data.size ? 'file' : 'directory'}"(name: node.data.name, size: node.data.size)
}
}