如何在Java中从SOAP XML字符串中获取多个值



我有一个SOAP XML,如下所示:

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope>
<soapenv:Header/>
<soapenv:Body>
<bcs:IntegrationEnquiryResultMsg>
<ResultHeader>
<cbs:ResultCode>0</cbs:ResultCode>
<cbs:ResultDesc>Operation successfully.</cbs:ResultDesc>
</ResultHeader>
<IntegrationEnquiryResult>
<bcs:Subscriber>
<bcs:SupplementaryOffering>
<bcc:OfferingKey>
<bcc:OfferingID>14205004</bcc:OfferingID>
<bcc:PurchaseSeq>300000000856956</bcc:PurchaseSeq>
</bcc:OfferingKey>
</bcs:SupplementaryOffering>
<bcs:SupplementaryOffering>
<bcc:OfferingKey>
<bcc:OfferingID>20220504</bcc:OfferingID>
<bcc:PurchaseSeq>300000000850496</bcc:PurchaseSeq>
</bcc:OfferingKey>
</bcs:SupplementaryOffering>
<bcs:SupplementaryOffering>
<bcc:OfferingKey>
<bcc:OfferingID>14205003</bcc:OfferingID>
<bcc:PurchaseSeq>300000000853681</bcc:PurchaseSeq>
</bcc:OfferingKey>
</bcs:SupplementaryOffering>
</bcs:Subscriber>
</IntegrationEnquiryResult>
</bcs:IntegrationEnquiryResultMsg>
</soapenv:Body>
</soapenv:Envelope>

我想要得到OfferingID的值。可能有多个,因为在这种情况下有3个。我试过下面的代码,但只得到了第一个。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();
System.out.println(getString("bcc:OfferingID", rootElement));
protected static String getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
for (Node node : iterable(list)) {
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
}
return null;
}
public static Iterable<Node> iterable(final NodeList nodeList) {
return () -> new Iterator<Node>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < nodeList.getLength();
}
@Override
public Node next() {
if (!hasNext())
throw new NoSuchElementException();
return nodeList.item(index++);
}
};
}
In this case, I only get `14205004`. Where am I missing a step? 
  1. getString方法的for循环中有一个node变量,您没有使用它,而是继续使用相同的元素list.item(0)

  2. 您在第一次迭代后立即返回,因此即使使用node变量修复了上述问题,您也只能获得第一个,因为您在第一个迭代时返回

  3. 你的方法返回一个字符串,它应该返回字符串列表

你可能想要下面这样的东西:

protected static List<String> getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
List<String> result = new ArrayList<>();

for (Node node : iterable(list)) {
result.add(node.getFirstChild().getNodeValue());
}
return result;
}

最新更新