我需要解析和打印 ns4:功能 部分。 Karate 以 json 格式打印它。我试着引用 this回答。但是,我得到'错误:'前缀'xsi'的命名空间尚未声明。'错误,如果使用建议的 xPath。 IE。,
* def list = $Test1/Envelope/Body/getPlan/planSummary/feature[1]
这是我的 XML:它包含许多具有不同“ns”值的部分,但我在这里给出了一个extraxt。
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns9:getPlan xmlns:ns10="http://xmlschema.test.com/xsd_v8" xmlns:ns9="http://xmlschema.test.com/srv/SMO_v4" xmlns:ns8="http://xmlschema.test.com/xsd/Customer_v2" xmlns:ns7="http://xmlschema.test.com/xsd/Customer/Customer_v4" xmlns:ns6="http://schemas.test.com/eca/common_types_2_1" xmlns:ns5="http://xmlschema.test.com/xsd/Customer/BaseTypes_1_0" xmlns:ns4="http://xmlschema.test.com/xsd_v4" xmlns:ns3="http://xmlschema.test.com/xsd/Enterprise/BaseTypes/types/ping_v1" xmlns:ns2="http://xmlschema.test.com/xsd/common/exceptions/Exceptions_v1_0">
<ns9:planSummary xsi:type="ns4:Plan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns5:code>XPBSMWAT</ns5:code>
<ns5:description>Test Plan</ns5:description>
<ns4:category xsi:nil="true"/>
<ns4:effectiveDate>2009-11-05</ns4:effectiveDate>
<ns4:sharingGroupList>
<ns4:sharingCode>CAD_DATA</ns4:sharingCode>
<ns4:contributingInd>true</ns4:contributingInd>
</ns4:sharingGroupList>
<ns4:feature>
<ns5:code>ABC</ns5:code>
<ns5:description>Service</ns5:description>
<ns5:descriptionFrench>Service</ns5:descriptionFrench>
<ns4:poolGroupId xsi:nil="true"/>
<ns4:switchCode/>
<ns4:type/>
<ns4:dtInd>false</ns4:dtInd>
<ns4:usageCharge>0.0</ns4:usageCharge>
<ns4:connectInd>false</ns4:connectInd>
</ns4:feature>
</ns9:planSummary>
</ns9:getPlan>
</S:Body>
</S:Envelope>
这是我使用的 xPath;
注意:我将上面的 xml 保存在单独的文件 test1.xml 中。我只是在阅读它并解析它的值。
* def Test1 = read('classpath:PP1/data/test1.xml')
* def list = $Test1/Envelope/Body/*[local-name()='getPlan']/*[local-name()='planSummary']/*[local-name()='feature']/*
* print list
这是我得到的回应;
16:20:10.729 [ForkJoinPool-1-worker-1] INFO com.intuit.karate - [print] [
"ABC",
"Service",
"Service",
"",
"",
"",
"false",
"0.0",
"false"
]
我怎样才能在 XML 中得到相同的结果?
请您参考如下方法:
这很有趣,我以前没见过。问题是你有一个带有命名空间的属性 xsi:nil="true"当您采用 XML 的子集但不再定义命名空间时,这会导致问题。如果您先将其删除,则一切正常。
试试这个:
* remove Test1 //poolGroupId/@nil
* def temp = $Test1/Envelope/Body/getPlan/planSummary/feature
您可以尝试的另一种方法是在执行 XPath 之前执行字符串替换以删除 XML 中的麻烦内容。
编辑:添加了有关如何使用 Java 进行字符串替换的信息。下面将删除整个
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns4:Plan"部分。
* string temp = Test1
* string temp = temp.replaceAll("xmlns:xsi[^>]*", "")
* print temp
所以你明白了。只需使用正则表达式。
另见: https://stackoverflow.com/a/50372295/143475

