未使用XmlSlurper名称空间

时间:2010-06-22 18:47:36

标签: xml groovy

我有一个XML模板文档:

<TriadMessage xmlns="http://www.myco.com/02/11/2008/V1/TriadMessage.xsd" 
        xmlns:triad="http://www.myco.com/02/11/2008/V1/TriadTypes.xsd" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<TriadRouteInfo>
   <triad:RoutingCorrelationId>new value goes here</triad:RoutingCorrelationId>
...

我使用Groovy 1.7阅读:

triadDoc = new XmlSlurper().parseText(xmlMessage).declareNamespace(
    tm: "http://www.myco.com/02/11/2008/V1/TriadMessage.xsd", 
    triad: "http://www.myco.com/02/11/2008/V1/TriadTypes.xsd", 
    xsi: "http://www.w3.org/2001/XMLSchema-instance"
    )
xmlBuilder = new StreamingMarkupBuilder()
writer = xmlBuilder.bind {mkp.yield triadDoc}

然后我在文档中插入值:

triadDoc.TriadRouteInfo.RoutingCorrelationId = dto.getReportRevisionId()
...

并输出:

writer.toString()

这就是我的文档:

<?xml version="1.0" encoding="UTF-8"?>
  <tm:TriadMessage xmlns:tm="http://www.myco.com/02/11/2008/V1/TriadMessage.xsd">
  <tm:TriadRouteInfo>
     <triad:RoutingCorrelationId xmlns:triad="http://www.myco.com/02/11/2008/V1/TriadTypes.xsd">24670</triad:RoutingCorrelationId>
...

请注意,每个元素都会出现三元组命名空间。这些线路很多(我这里只展示一条线路)。我希望NS只在顶部声明,并通过下面的三元组:引用。我做错了什么?

1 个答案:

答案 0 :(得分:1)

试过这个:

import groovy.xml.StreamingMarkupBuilder

def xml = """
<TriadMessage xmlns="http://www.myco.com/02/11/2008/V1/TriadMessage.xsd" 
                           xmlns:triad="http://www.myco.com/02/11/2008/V1/TriadTypes.xsd" 
                           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <TriadRouteInfo>
    <triad:RoutingCorrelationId>new value goes here</triad:RoutingCorrelationId>
  </TriadRouteInfo>
</TriadMessage>"""


def triadDoc = new XmlSlurper().parseText( xml ).declareNamespace(
  tm:    "http://www.myco.com/02/11/2008/V1/TriadMessage.xsd", 
  triad: "http://www.myco.com/02/11/2008/V1/TriadTypes.xsd", 
  xsi:   "http://www.w3.org/2001/XMLSchema-instance" )

def xmlBuilder = new StreamingMarkupBuilder()
writer = xmlBuilder.bind {
  mkp.declareNamespace( tm:    "http://www.myco.com/02/11/2008/V1/TriadMessage.xsd" )
  mkp.declareNamespace( triad: "http://www.myco.com/02/11/2008/V1/TriadTypes.xsd" )
  mkp.declareNamespace( xsi:   "http://www.w3.org/2001/XMLSchema-instance" )
  mkp.yield triadDoc
}

triadDoc.TriadRouteInfo.RoutingCorrelationId = 'wheeee'

println writer

它打印出来(由我装扮,所以不是全部都在一行):

<tm:TriadMessage xmlns:tm='http://www.myco.com/02/11/2008/V1/TriadMessage.xsd'
                 xmlns:triad='http://www.myco.com/02/11/2008/V1/TriadTypes.xsd'
                 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
  <tm:TriadRouteInfo>
    <triad:RoutingCorrelationId>wheeee</triad:RoutingCorrelationId>
  </tm:TriadRouteInfo>
</tm:TriadMessage>

有什么好处吗?