开发者

Groovy Xml Parsing with namespaces

开发者 https://www.devze.com 2023-01-14 21:23 出处:网络
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 wit

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'开发者_StackOverflow中文版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()
   }


from groovy documentation

def wsdl = '''
<definitions name="AgencyManagementService"
    xmlns:ns1="http://www.example.org/NS1"
    xmlns:ns2="http://www.example.org/NS2">
    <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()
0

精彩评论

暂无评论...
验证码 换一张
取 消