如何说服 groovy.xml.MarkupBuilder 创建一个名为 'use' 的节点

How to convince groovy.xml.MarkupBuilder to create a node whose name is 'use'

SVG 定义了一个名为 use 的元素,我正在尝试使用 groovy.xml.MarkupBuilder 生成一个 SVG 文件,它利用了这个标签:

http://tutorials.jenkov.com/svg/defs-element.html

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.svg {
    defs {
        g(id:"shape") {
            rect(x:50, y:50, width:50, height:50)
            circle(cx:50, cy:50, r:50)
        }
    }

    use("xlink:href":"#shape", x:50,  y:50")
}

然而 use 也是 groovy 中的关键字。如何正确转义?

不确定这些方法是官方的,但它们有效:

v1:

def xml = new groovy.xml.MarkupBuilder()

xml.svg {
    defs {
        g(id:"shape") {
            rect(x:50, y:50, width:50, height:50)
            circle(cx:50, cy:50, r:50)
        }
    }
    createNode('use',["xlink:href":"#shape", x:50,  y:50])
    //nested elements could be here
    nodeCompleted('svg','use')
}

v2:

def xml = new groovy.xml.MarkupBuilder()

xml.svg {
    defs {
        g(id:"shape") {
            rect(x:50, y:50, width:50, height:50)
            circle(cx:50, cy:50, r:50)
        }
    }

    doInvokeMethod('use','use',[["xlink:href":"#shape", x:50,  y:50], { 
        /*nested elements could be here*/ 
    } ])
}

v3:

我们可以重新定义 getName 负责进行名称映射或检查转义规则的方法。

@groovy.transform.CompileStatic
class MyMarkupBuilder  extends groovy.xml.MarkupBuilder{
    def getName(String name){
        if(name.startsWith('__'))return name.substring(2)
        return name
    }
}

def xml = new MyMarkupBuilder()

xml.svg {
    defs {
        g(id:"shape") {
            rect(x:50, y:50, width:50, height:50)
            circle(cx:50, cy:50, r:50)
        }
    }
    __use("xlink:href":"#shape", x:50,  y:50)
}