views:

403

answers:

1

Hi, I'm working on a XML-document with Groovy and test a node for a certain attribute, which has a namespace prefix. How could it work:

in groovy-script:

...
Element.Subelement.each {
  if (it.'@type'=='ns2:xyType')
    ...do what ever...
}

in XML document:

<Element>
   <Subelement xsi:type="ns2:xyType"> 
      <!-- or another type, want to do something with      
           subelement only if type is "ns2:xyType" -->
   </Subelement>
</Element>

Looking for something like:

if (it.'@xsi:type'=='ns2:xyType')

THX Seldon

A: 

Well, your document is a little confusing, since it seems that neither xsi nor ns2 namespaces were ever declared, but I'm going to assume they were declared somewhere in the complete doc.

From The Groovy Docs

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()

For your example (note, you'll have to fill in the URLs for the namespaces):

def ggg = '''
<Element xmlns:xsi="http://www.example.org/xsi"
    xmlns:ns2="http://www.example.org/NS2"&gt;
   <Subelement xsi:type="ns2:xyType"> 
      <SubSub name="bob" />
   </Subelement>
</Element>
'''
def xml = new XmlSlurper().parseText(ggg).declareNamespace(xsi: 'http://www.example.org/xsi', ns2: 'http://www.example.org/NS2')
def elem = xml.'Subelement'
if ( elem.'@xsi:type'.text() == 'ns2:xyType' ){
   // do it  
}
Bill James