Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve element value from SOAP response using Java?

Tags:

java

soap

xml

I am trying to get the tag value from the below String response getting from salesforce,

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata">
   <soapenv:Body>
      <listMetadataResponse>
         <result>
            <createdById>00528000001m5RRAAY</createdById>
            <createdByName>Hariprasath Thanarajah</createdByName>
            <createdDate>1970-01-01T00:00:00.000Z</createdDate>
            <fileName>objects/EmailMessage.object</fileName>
            <fullName>EmailMessage</fullName>
            <id />
            <lastModifiedById>00528000001m5RRAAY</lastModifiedById>
            <lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
            <lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
            <namespacePrefix />
            <type>CustomObject</type>
         </result>
      </listMetadataResponse>
   </soapenv:Body>
</soapenv:Envelope>

Above we had the tag <fullName>. I'll need to get the value inside the tag and put it in the String array. I have tried with substring method but It returns only one value. Can anyone suggest me to do this?

like image 832
Hariprasath Avatar asked Jan 05 '23 14:01

Hariprasath


2 Answers

I have tried like below,

public static Document loadXMLString(String response) throws Exception
{
    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(response));

    return db.parse(is);
}

public static List<String> getFullNameFromXml(String response, String tagName) throws Exception {
    Document xmlDoc = loadXMLString(response);
    NodeList nodeList = xmlDoc.getElementsByTagName(tagName);
    List<String> ids = new ArrayList<String>(nodeList.getLength());
    for(int i=0;i<nodeList.getLength(); i++) {
        Node x = nodeList.item(i);
        ids.add(x.getFirstChild().getNodeValue());             
        System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
    }
    return ids;
}

From above code, you will get ids list. After that, you can put those into the String Array and return those into String array like below,

List<String> output = getFullNameFromXml(response, "fullName");
String[] strarray = new String[output.size()];
output.toArray(strarray);
System.out.print("Response Array is "+Arrays.toString(strarray));
like image 197
Hariprasath Avatar answered Jan 26 '23 02:01

Hariprasath


Use the below code for parsing the SOAP response and getting the element value.
Save the XML response at any location on your system.Call the method getResult(). It is a generic method . It takes the payload class type of webservice response and returns the java object.

File xmlFile = new File("response file path from step 1");    
Reader fileReader = new FileReader(xmlFile);    
BufferedReader bufReader = new BufferedReader(fileReader);    
StringBuilder sb = new StringBuilder();    
String line = bufReader.readLine();    
while (line != null) {    
sb.append(line).append("\n");    
line = bufReader.readLine();    
}    
String xml2String = sb.toString();           
bufReader.close();

public <T> T getResult(String xml, String path, Class<T> type) {    
final Node soapBody = getSoapBody(xml, path);    
return getInstance(soapBody, type);    
}    
private Node getSoapBody(String xml, String path) {     
try {    
SOAPMessage message = getSoapMessage(xml, path);    
Node firstElement = getFirstElement(message);    
return firstElement;     
}    
catch (Exception e) {    
throw new RuntimeException(e);    
}    
}     
private SOAPMessage getSoapMessage(String xml, String path) throws SOAPException, 
IOException {    
MessageFactory factory = MessageFactory.newInstance();    
FileInputStream fis = new FileInputStream(path);    
BufferedInputStream inputStream = new BufferedInputStream(fis);    
return factory.createMessage(new MimeHeaders(), inputStream);    
}    
private Node getFirstElement(SOAPMessage message) throws SOAPException {    
final NodeList childNodes = message.getSOAPBody().getChildNodes();    
Node firstElement = null;    
for (int i = 0; i < childNodes.getLength(); i++) {    
if (childNodes.item(i) instanceof Element) {    
firstElement = childNodes.item(i);    
break;    
}    
}    
return firstElement;    
}    
private <T> T getInstance(Node body, Class<T> type) {    
try {    
JAXBContext jc = JAXBContext.newInstance(type);    
Unmarshaller u = jc.createUnmarshaller();    
return (T) u.unmarshal(body);    
}    
catch (JAXBException e) {    
throw new RuntimeException(e);    
}    
}    
like image 25
Abhishek Jha Avatar answered Jan 26 '23 03:01

Abhishek Jha