加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Groovy MarkupBuilder中使用命名空间

发布时间:2020-12-14 16:26:06 所属栏目:大数据 来源:网络整理
导读:我想要以下输出: ?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:testerZH/structure:tester structure:surveyYear2001/stru
我想要以下输出:

<?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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读