【问题标题】:Use of Namespaces in Groovy MarkupBuilder在 Groovy MarkupBuilder 中使用命名空间
【发布时间】:2011-04-10 15:05:22
【问题描述】:

我想要以下输出:

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

它的语法正确,但是当你有很多节点时不好看。

【问题讨论】:

    标签: groovy namespaces markupbuilder


    【解决方案1】:

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

    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>
    

    【讨论】:

    • 如何声明mkp
    • 这里是mkp 一个特殊的命名空间,用于脱离构建器的正常构建模式并访问辅助标记方法'yield'、'pi'、'comment'、'out', “命名空间”、“xmlDeclaration”和“yieldUnescaped”。
    猜你喜欢
    • 2022-03-23
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多