Groovy Xml解析命名空间

Groovy Xml解析命名空间

问题描述:

我一直在尝试用groovy的XML Slurper做一些xml修改。Groovy Xml解析命名空间

基本上,我正在通过XML寻找标签或属性有?作为价值,然后用一些价值取代它。

我已经得到它为没有命名空间的xml工作,但是一旦我包含它们的东西就会变得不可靠。例如,这样的:

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>"; 

生产:

<Envelope/>

下面是我使用的Groovy代码。这确实出现时,我没有使用一个命名空间的工作:

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

从常规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

谢谢,我看到的文档,但是与该问题是,我通过多种运行XML字符串,我不是的内容。他们可能有也可能没有名字空间,并且他们有不同的标签。 我有什么可以找到元素就好了,当我尝试和更新它时失败。 – eric 2010-09-03 13:17:47

+0

我认为第一个问题是你的代码只是获得根节点,这就是为什么你只看到作为回应 – 2010-09-03 16:56:25