Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Namespaces in Groovy MarkupBuilder

I want have the following output:

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

I can add namespace to an xml like this:

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

But how I can make a namespace prefix to an xml-element? The only solution I found was this:

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

But this gives me the follwing output:

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

It's syntactical correct, but not nice to read when you have many nodes.

like image 365
haschibaschi Avatar asked Sep 10 '10 08:09

haschibaschi


1 Answers

You can do this (not sure it's what you want though)

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 )

That code outputs:

<?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>
like image 195
tim_yates Avatar answered Oct 21 '22 22:10

tim_yates