Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import java.io.

File;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class SoapXmlUpdater {


private static final String API_BASE_URI = "http://example.com/api";
private static final String API_PATH = "/endpoint";

public static void main(String[] args) {


// Load the SOAP XML file into a DOM parser
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(new File("path/to/soap.xml"));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}

// Use the DOM parser to find and update the desired tag values in the XML
if (document != null) {
Node messageTypeNode =
document.getElementsByTagName("MessageType").item(0);
messageTypeNode.setTextContent("NewMessageType");
Node messageIDNode =
document.getElementsByTagName("MessageID").item(0);
messageIDNode.setTextContent("NewMessageID");
}

// Serialize the updated DOM back into an XML string


String updatedXml = documentToString(document);

// Send a REST API request with the updated XML as the request body
RequestSpecification request =
RestAssured.given().baseUri(API_BASE_URI).contentType(ContentType.XML);
HashMap<String, String> headers = new HashMap<>();
headers.put("header1", "value1");
headers.put("header2", "value2");
request.headers(headers);
request.body(updatedXml);
Response response = request.post(API_PATH);
System.out.println(response.getStatusCode());
}

// Helper method to serialize a DOM to an XML string


private static String documentToString(Document document) {
try {
javax.xml.transform.TransformerFactory tf =
javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = tf.newTransformer();

transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION,
"yes");
java.io.StringWriter writer = new java.io.StringWriter();
transformer.transform(new javax.xml.transform.dom.DOMSource(document),
new javax.xml.transform.stream.StreamResult(writer));
return writer.getBuffer().toString().replaceAll("\n|\r", "");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

///////////////////////////////////////////////////////////////////////////////////
/////////////

You might also like