【问题标题】:Groovy Xml Parsing with namespaces使用命名空间进行 Groovy Xml 解析
【发布时间】:2011-04-07 16:06:32
【问题描述】:

我一直在尝试使用 groovy 的 XML Slurper 进行一些 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>";

产生:

&lt;Envelope/&gt;

这是我正在使用的 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()
   }

【问题讨论】:

    标签: groovy xmlslurper


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我在文档中看到了这一点,但问题是我正在运行多个我不包含内容的 XML 字符串。它们可能有也可能没有命名空间,并且有不同的标签。我所拥有的可以很好地找到元素,当我尝试更新它时它会失败。
    • 我认为第一个问题是你的代码只获取根节点,这就是为什么你只看到 作为响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2014-01-10
    • 2010-11-08
    • 2018-07-15
    相关资源
    最近更新 更多