如何在没有名称空间的SoapUI Groovy中从Soap Response中提取XML节点?

时间:2018-02-07 10:05:43

标签: xml soap groovy soapui xmlslurper

我想从下面的XML中提取2个节点Insu和/ Insu之间的数据而不使用输出中的命名空间

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
  <Qres xmlns="http://www.test.com/h/xsd">
     <PMR xmlns:xsd="http://www.test.com/h/xsd">
        <ID xmlns="http://example.services/Results.xsd" xmlns:ns1="urn:Group/20160505/Ons" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">1159</ID>
        <ref xmlns="http://example.services/Results.xsd" xmlns:ns1="urn:Group/20160505/Ons" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">12345</ref>
        <SingleQres xmlns="http://example.services/Results.xsd" xmlns:ns1="urn:Group/20160505/AddOns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
           <Qres>
              <ref>12345</ref>
              <SC>ok</SC>
              <Sche>
                    <csc>Car</csc>
                    <Insu>
                 <Entry>
                          <Key>ok</Key>
                          <Value>hello</Value>
                          <MetData>
                             <Key>test</Key>
                             <Value>test</Value>
                          </MetData>
                       </Entry>
                    </Insu>
              </Sche>
           </Qres>
        </SingleQres>
     </PMR>
  </Qres>

我写了下面的代码并且能够得到它。 Years是测试步骤的名称,其结果高于XML

def c=context.expand('${Years#Response#//*:Qres//*:Sche//*:Insu/*}')
log.info c

输出低于

<res:Entry xmlns:res="http://example.services/Results.xsd">

                          <res:Key>ok</res:Key>
                          <res:Value>hello</res:Value>
                          <res:MetData>
                             <res:Key>test</res:Key>
                             <res:Value>test</res:Value>
                          </res:MetData>
                       </res:Entry>

问题: - 它附加了命名空间。

我希望XML 没有,只有下面的节点应该像原始XML那样存在

   <Entry>
   <Key>ok</Key>
   <Value>hello</Value>
   <MetData>
   <Key>test</Key>
   <Value>test</Value

如果使用上面的命令进行一些调整会很好,我可以得到没有名称空间的节点,因为我想在后续步骤中使用这些值没有名称空间前缀

2 个答案:

答案 0 :(得分:1)

您可以使用不带名称空间的XmlSlurperXmlUtil来序列化,如下所示:

def xml = new XmlSlurper(false, false).parseText(context.expand('${Years#Response}'))
log.info groovy.xml.XmlUtil.serialize(xml.'**'.find{it.name() == 'Insu'}.children())

您可以在线快速尝试 demo

编辑:基于OP评论。

XmlNodePrinter用于在没有xml标记声明的情况下获取它。

def xml = new XmlParser(false, false).parseText(context.expand('${Years#Response}'))
def entry = xml.'**'.find{it.name() == 'Entry'}
def sw = new StringWriter()
new XmlNodePrinter(new PrintWriter(sw)).print(entry)
log.info sw.toString()

以下是demo

答案 1 :(得分:1)

@Rao提供的解决方案也很有效。谢谢你的详细解释。

我正在使用下面的解决方案,我觉得它更容易理解并适用于上面的示例XML

 def groovyUtils=new com.eviware.soapui.support.GroovyUtils(context)
 def res = groovyUtils.getXmlHolder("Years#Response")
 def xmlData = res.getXmlObject()
 String str=xmlData.toString()
 def a=str.split("<Insu>")[1].split("</Insu>")
 log.info a[0] 

@ Rao的回答也很好