首页 > 解决方案 > 在 Java 8 中使用名称空间读取 Soap 响应

问题描述

我想阅读 AccountNumber、OrderNumber、responseCode 和 responseDescription。我可以阅读 AccountNumber,OrderNumber 使用

public static String getTagContents(String xmlString, String tagName) {
    String resp = "";
    String bTagName = "<" + tagName + ">";
    int stInd = xmlString.indexOf(bTagName);
    int enInd = xmlString.indexOf("</" + tagName + ">");
    if (stInd > -1 && enInd > -1) {
        resp = xmlString.substring(stInd + bTagName.length(), enInd);
    }
    return resp;
}

responseCode 和 responseDescription 同样失败

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
   <env:Body>
      <eSAResponse xmlns="http://www.www.someurl.com/ESA">
         <eSAResponseData>
            <AccountNumber>45300895</AccountNumber>
            <OrderNumber />
         </eSAResponseData>
         <commonResponse>
            <responseCode xmlns="http://www.someurl.com">00</responseCode>
            <responseDescription xmlns="http://www.someurl.com/ESAASDmmonTypes">Success</responseDescription>
         </commonResponse>
      </eSAResponse>
   </env:Body>
</env:Envelope>

标签: soapjava-8

解决方案


因为您正在标签处寻找确切的字符串值。代码适用于 AccountNumber,因为标签没有附加值。另一方面,responseCode 标记的确切字符串值如下:

<responseCode xmlns="http://www.someurl.com">

我相信你绝对应该使用像DOMParser这样的通用库

如果您真的想使用自己的代码,可以应用此解决方案:

public static String getTagContents(String xmlString, String tagName) {
        String resp = "";
        String bTagName = "<" + tagName;
        int stInd = xmlString.indexOf(bTagName);
        int enInd = xmlString.indexOf("</" + tagName);
        if (stInd > -1 && enInd > -1) {
            resp = xmlString.substring(stInd + bTagName.length(), enInd);
        }
        return resp.split(">")[1];
    }

推荐阅读