我正在使用groovy和groovy.xml.MarkupBuilder编写一个库,我将用它来自动创建epub文件。我正在编写一个可用于生成container.xml文件的函数,我注意到当我尝试使用带有连字符的属性名称时,我的IDE给出了一个错误,而不是当属性名称没有&#时39;有一个连字符。
def writer = new StringWriter();
def xml = new MarkupBuilder(writer);
def fullPath="full-path"
def mediaType="media-type"
def generateContainer()
{
xml.xmlDeclaration()
xml.container(version:'1.0', xmlns:'urn:oasis:names:tc:opendocument:xmlns:container')
{
rootfiles
{
rootfile( this.fullPath:'OEBPS/content.opf',this.mediaType:'application/oebps-package+xml')
}
}
}
当我尝试使用
时full-path
我发错了。当我尝试使用
时fullpath
它没有给我一个错误。
为什么会发生这种情况,我该如何纠正?见here
The value of full-path (in bold) is the only part of this file that will ever vary.
我希望尽可能准确
答案 0 :(得分:1)
这可以按预期工作:
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
def fullPath = "full-path"
def mediaType = "media-type"
xml.mkp.xmlDeclaration( version: "1.0", encoding: "utf-8" )
xml.container( version:'1.0',
xmlns:'urn:oasis:names:tc:opendocument:xmlns:container' ) {
rootfiles {
rootfile( (fullPath) : 'OEBPS/content.opf',
(mediaType): 'application/oebps-package+xml' )
}
}
println writer
确保在引用变量fullPath
时,必须使用(fullPath)
[大括号]才能在xml节点中使用变量的值作为属性。
答案 1 :(得分:1)
您可以引用具有非法标识符字符的元素和属性名称:
import groovy.xml.MarkupBuilder
def writer = new StringWriter();
def xml = new MarkupBuilder(writer);
xml.container(version:'1.0', xmlns:'urn:oasis:names:tc:opendocument:xmlns:container') {
"root-files" {
"root-file"( "full-path" :'OEBPS/content.opf',
"media-type" :'application/oebps-package+xml')
}
}
def result = writer.toString()
assert result.contains('full-path')
assert result.contains('media-type')