Created
May 3, 2015 09:03
-
-
Save clement-bramy/95b64e72619f6090638e to your computer and use it in GitHub Desktop.
How to extract SOAP message's body's content as a new XML document.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.semvoz.jdk8.jdom; | |
import org.jdom2.Document; | |
import org.jdom2.Element; | |
import org.jdom2.JDOMException; | |
import org.jdom2.Namespace; | |
import org.jdom2.filter.Filters; | |
import org.jdom2.input.SAXBuilder; | |
import org.jdom2.output.Format; | |
import org.jdom2.output.XMLOutputter; | |
import org.jdom2.xpath.XPathExpression; | |
import org.jdom2.xpath.XPathFactory; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.io.IOException; | |
import java.io.StringReader; | |
import java.util.Arrays; | |
import java.util.List; | |
/** | |
* Created by Clement Bramy on 3/05/15. | |
* Created for project: jdk8-tutorial | |
* | |
* Soap message: | |
<?xml version="1.0"?> | |
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> | |
<soap:Body xmlns:m="http://www.example.org/stock"> | |
<m:GetStockPriceResponse> | |
<m:Price>34.5</m:Price> | |
</m:GetStockPriceResponse> | |
</soap:Body> | |
</soap:Envelope> | |
*/ | |
public class Main { | |
private final static Logger logger = LoggerFactory.getLogger(Main.class); | |
// Namespaces | |
private final static List<Namespace> namespaces = Arrays.asList( | |
Namespace.getNamespace("m", "http://www.example.org/stock"), | |
Namespace.getNamespace("soap", "http://www.w3.org/2001/12/soap-envelope") | |
); | |
// Xpath | |
private final static String SOAP_BODY_CONTENT_XPATH = "/soap:Envelope/soap:Body/m:GetStockPriceResponse"; | |
public static void main(final String [] args) throws JDOMException, IOException { | |
final String stockXml = LocalSoapUtil.getSoapMessage("stock-price-response.xml"); | |
final SAXBuilder builder = new SAXBuilder(); | |
final Document document = builder.build(new StringReader(stockXml)); | |
final XPathFactory factory = XPathFactory.instance(); | |
final XPathExpression<Element> expression = factory.compile(SOAP_BODY_CONTENT_XPATH, Filters.element(), null, namespaces); | |
final Element response = expression.evaluateFirst(document); | |
logger.info("\n" + new XMLOutputter(Format.getPrettyFormat()).outputString(new Document(response.detach()))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment