6

我想要以下输出:

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

它在语法上是正确的,但当你有很多节点时就不太好读了。

4

1 回答 1

12

你可以这样做(虽然不确定这是你想要的)

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>
于 2010-09-10T09:51:46.053 回答