简体   繁体   English

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

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

SVG defines an element named use and I am trying to generate an SVG file using groovy.xml.MarkupBuilder that takes advantage of this tag: SVG定义了一个名为use的元素,我正在尝试使用groovy.xml.MarkupBuilder来利用此标记来生成SVG文件:

http://tutorials.jenkov.com/svg/defs-element.html 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")
}

However use is also a keyword in groovy. 但是, use也是groovy中的关键字。 How do I escape it correctly? 如何正确逃脱?

not sure those methods are official however they work: 不确定这些方法是否正式,但是它们是否有效:

v1: 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: 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: v3:

we could redefine getName method that is responsible to do names mapping or check escaping rules. 我们可以重新定义负责名称映射或检查转义规则的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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM