首页 > 解决方案 > 空手道 - 使用命名空间解析 XML

问题描述

我需要解析和打印ns4:feature部分。空手道以 json 格式打印它。我试着参考这个答案。但是,我得到'错误:'前缀'xsi'的命名空间尚未声明。' 错误,如果使用建议的 xPath。IE,

* def list = $Test1/Envelope/Body/getPlan/planSummary/feature[1]

这是我的 XML:它包含许多具有不同 'ns' 值的部分,但我在这里给出了一个外文。

<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 中得到相同的结果?

标签: xpathkarate

解决方案


这很有趣,我以前没见过。问题是您有一个带有名称空间的属性,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


推荐阅读