I have a SOAP XML as below:
<?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>
I would want to get the values of OfferingID
. There could be multiple as in this case there are 3. I have tried the code below but I only get the first one.
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?
CodePudding user response:
You have a
node
variable in the for loop of yourgetString
method which you don't use, instead you keep using the same elementlist.item(0)
You return immediately after the first iteration, so even if you fix the above issue withe
node
variable you will get only the first because you return on the first iterationYour method returns a string where it should return a list of strings
Something like below might be what you want:
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;
}