2010-09-10 44 views
4

我想有以下的輸出:使用命名空間中的Groovy MarkupBuilder的

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

但是,這給了我follwing輸出:

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

這句法正確,但不是很好看,當你有很多節點。

回答

9

你可以做到這一點(不知道這是你想要什麼,雖然)

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> 
+0

葉氏不,謝謝。 – haschibaschi 2010-09-10 12:39:44

+0

如何聲明'mkp'? – 2016-06-01 15:17:51