Scala:使用回调以编程方式创建xml?

时间:2021-01-11 12:40:53

I have a library that runs through a tree structure using callbacks into a class. A simplified variant is:

我有一个库,它通过一个树结构运行回调到一个类。简化的变体是:

class CallBack {
    openGroup(name:String)
    closeGroup(name:String)
    item(name:String)
}

openGroup thus steps one step into the tree, closeGroup steps out and item are leafs. What I would like to to is to create a simple xml structure as I run through the code. A naive solution would be to simply do something like the below pseudocode:

openGroup因此在树中执行一步,closeGroup跳出并且item是叶子。我想要的是在我运行代码时创建一个简单的xml结构。一个天真的解决方案是简单地执行类似下面的伪代码:

class CallBack {
    var xml:String = ""
    openGroup(name:String)  = { xml += "<ol label=" + name + ">"}
    closeGroup(name:String) = { xml += "</ol>" }
    item(name:String)       = { xml += "<li name=.... />" }
}

I guess a nicer solution would be to create this using Node:s, Groups etc., or other relevant technique and then create the xml.

我想一个更好的解决方案是使用Node:s,Groups等或其他相关技术创建它,然后创建xml。

Do you have any idea how to create xml from the above in some decent manner?

你知道如何从上面以一些体面的方式创建xml吗?

1 个解决方案

#1


1  

If you use JATL, it would look something like

如果你使用JATL,它看起来就像

class CallBack(writer: Writer) {
    private val html = new Html(writer)
    def openGroup(name:String) = html.ol.label(name)
    def closeGroup(name:String) = html.end
    def item(name:String) = html.li.label(name).end
}

#1


1  

If you use JATL, it would look something like

如果你使用JATL,它看起来就像

class CallBack(writer: Writer) {
    private val html = new Html(writer)
    def openGroup(name:String) = html.ol.label(name)
    def closeGroup(name:String) = html.end
    def item(name:String) = html.li.label(name).end
}