为什么这个 XPath(目标的所有节点)在响应中看不到元素(使用 SoapUI)?

Why this XPath (all nodes to the target) can not see element in response (with SoapUI)?

这是我尝试使用 脚本 (groovy) 断言探索的 xml 响应:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <myInfoResponse xmlns="http://test.test.test.test">
         <pc>1234223234</pc>
         <item>
            <sl>val1</sl>
            <he>val2</he>
            <ko>val3</ko>
            <fo>val4</fo>
            <ok>val5</ok>
            <di>val6</di>
         </item>
...

为什么我无法通过以下方式获取 pc 节点的值:

def holder = new XmlHolder( messageExchange.responseContentAsXml )
holder.getNodeValue("/S:Envelope/S:Body/myInfoResponse/pc")
// Output: null
holder.getNodeValue("/S:Envelope/S:Body/myInfoResponse[1]/pc[1]")
// Output: null

而且我可以通过 XPath 获取值

holder.getNodeValue("/S:Envelope/S:Body/*[1]/*[1]")
// Output: 1234223234
holder.getNodeValue("/S:Envelope/S:Body/*[1]/*[2]/*[4]")
// Output: val4

为什么?

仍然不知道如何让 holder.getNodeValue() 工作,但我发现 XmlSlurper 中工作正常。

Groovy docs "Processing XML"

def Envelope = new XmlSlurper().parseText(messageExchange.responseContentAsXml)
log.info("pc = " + Envelope.Body.myInfoResponse.pc.text())
// Output: 1234223234

正如评论中提到的,元素 myInfoResponse 具有默认命名空间。这就是为什么您无法获得 pc.

的值的原因

下面是使用 getNodeValue

的脚本断言
//Check if the response is not empty
assert context.response, 'Response is empty or null'

def holder = new com.eviware.soapui.support.XmlHolder(context.response)
//You may also change the prefix other than mentioned in the response like below
holder.declareNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/')
//Below namespace uri does not have prefix in the response, but now setting prefix as ns
holder.declareNamespace('ns', 'http://test.test.test.test')
def pcValue = holder.getNodeValue('//soap:Envelope/soap:Body/ns:myInfoResponse/ns:pc')
log.info "Response of has pc value : ${pcValue}" 

使用 XmlSlurper

assert context.response
def parsedXml = new XmlSlurper().parseText(context.response)
def pcValue = parsedXml.'**'.find {it.name() == 'pc'}.text()
log.info "Response of has pc value : ${pcValue}" 
//Similarly you can find any element name, for example item/fo
def foVal = parsedXml.'**'.find {it.name() == 'fo'}.text()
log.info "fo value is : ${foVal}"