views:

129

answers:

1

Hi, I've been trying to do some xml modifications with groovy's XML Slurper.

Basically, i'm going through the xml and looking for tags or attributes that have ? as the value and then replacing it with some value.

I've got it working for xml that doesn't have namespaces but once I include them things get wonky. For example, this:

   String foo = "<xs:test xmlns:xs="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:foo="http://myschema/xmlschema" name='?'>
        <foo:tag1>?</foo:tag1>
        <foo:tag2>?</foo:tag2>
    </xs:test>";

produces:

<Envelope/>

Here's the groovy code I'm using. This does appear to work when I am not using a namespace:

 public def populateRequest(xmlString, params) {

     def slurper = new XmlSlurper().parseText(xmlString)
     //replace all tags with ?
     def tagsToReplace = slurper.depthFirst().findAll{ foundTag ->
        foundTag.text() == "?"
     }.each { foundTag ->
        foundTag.text = {webServiceOperation.parameters[foundTag.name()]}
       foundTag.replaceNode{
            "${foundTag.name()}"(webServiceOperation.parameters[foundTag.name()])
        }
      }
      //replace all attributes with ?
      def attributesToReplace = slurper.list().each{
          it.attributes().each{ attributes ->
          if(attributes.value == '?')
          {
            attributes.value = webServiceOperation.parameters[attributes.key]
          }
        }
      }

      new StreamingMarkupBuilder().bind { mkp.yield slurper }.toString()
   }
+1  A: 

from groovy documentation

def wsdl = '''
<definitions name="AgencyManagementService"
    xmlns:ns1="http://www.example.org/NS1"
    xmlns:ns2="http://www.example.org/NS2"&gt;
    <ns1:message name="SomeRequest">
        <ns1:part name="parameters" element="SomeReq" />
    </ns1:message>
    <ns2:message name="SomeRequest">
        <ns2:part name="parameters" element="SomeReq" />
    </ns2:message>
</definitions>
'''

def xml = new XmlSlurper().parseText(wsdl).declareNamespace(ns1: 'http://www.example.org/NS1', ns2: 'http://www.example.org/NS2')
println xml.'ns1:message'.'ns1:part'.size()
println xml.'ns2:message'.'ns2:part'.size()
Aaron Saunders
Thanks, i saw that in the documentation but the issue with that is that i'm running through multiple XML strings that i don't the contents of. They may or may not have namespaces, and they have different tags. What i have can find elements just fine, it fails when i try and update it.
eric
i think the first problem is that you code is only getting the root node, that is why you are only seeing <Envelope/> as a response
Aaron Saunders