gpt4 book ai didi

groovy - 在 Groovy MarkupBuilder 中使用命名空间

转载 作者:行者123 更新时间:2023-12-02 08:42:56 24 4
gpt4 key购买 nike

我想要以下输出:

<?xml version="1.0" encoding="UTF-8"?>
<structure:structuralDataRoot xmlns:register="http://www.test.ch/register/1" xmlns:structure="http://test.ch/structure/1" >
<structure:tester>ZH</structure:tester>
<structure:surveyYear>2001</structure:surveyYear>
<structure:surfaceData>
<structure:houseSurfaceData>
<structure:creationDate>2001-01-01</structure:creationDate>
<structure:localFarmId>
<register:houseIdCategory>token</register:houseIdCategory>
<register:houseId>token</register:houseId>
</structure:localFarmId>
</structure:houseSurfaceData>
</structure>

我可以将命名空间添加到 xml,如下所示:

xml.records('xmlns:structure' :"http://test.ch/structure/1" ...

但是如何为 xml 元素创建命名空间前缀呢?我找到的唯一解决方案是:

tester('xmlns:structure' :"http://test.ch/structure/1", 'ZH')

但这给了我以下输出:

<tester xmlns:structure='http://test.ch/structure/1'>ZH</tester>

语法正确,但当你有很多节点时,阅读起来不太好。

最佳答案

你可以这样做(但不确定这是否是你想要的)

import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil

def xmlBuilder = new StreamingMarkupBuilder()
writer = xmlBuilder.bind {
mkp.declareNamespace( register: "http://www.test.ch/register/1" )
mkp.declareNamespace( structure: "http://test.ch/structure/1" )
'structure:structuralDataRoot' {
'structure:tester'( 'ZH' )
'structure:surveyYear'( 2001 )
'structure:surfaceData' {
'structure:houseSurfaceData' {
'structure:creationDate'( '2001-01-01' )
'structure:localFarmId' {
'register:houseIdCategory'( 'token' )
'register:houseId'( 'token' )
}
}
}
}
}

println XmlUtil.serialize( writer )

该代码输出:

<?xml version="1.0" encoding="UTF-8"?>
<structure:structuralDataRoot xmlns:register="http://www.test.ch/register/1" xmlns:structure="http://test.ch/structure/1">
<structure:tester>ZH</structure:tester>
<structure:surveyYear>2001</structure:surveyYear>
<structure:surfaceData>
<structure:houseSurfaceData>
<structure:creationDate>2001-01-01</structure:creationDate>
<structure:localFarmId>
<register:houseIdCategory>token</register:houseIdCategory>
<register:houseId>token</register:houseId>
</structure:localFarmId>
</structure:houseSurfaceData>
</structure:surfaceData>
</structure:structuralDataRoot>

关于groovy - 在 Groovy MarkupBuilder 中使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3683042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com