How do i find an xml node and insert one or more nodes right below that node?
Here is a sample xml:
<HomeOwnersContext xmlns="http://schemas.datacontract.org/2004/07/Homesite.Homeowners.ContextModel.Api.Context" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <DisplayOnlyData/>
<QuoteData>
<animalsBitten>false</animalsBitten>
<burglarAlarm>No</burglarAlarm>
<businessOnPremises>false</businessOnPremises>
<totalNumberOfPeople>2</totalNumberOfPeople>
</QuoteData>
<QuoteHeader>
<Channel>Direct_Web</Channel>
<FormCode>3</FormCode>
</QuoteHeader>
</HomeOwnersContext>
Now i want to find <burglarAlarm> node and insert the below node
<cancelledForNonPay>1</cancelledForNonPay> right below that node.
Here's a quick groovy script that kind of does what
// get the request and its content content of the test // Adjust "TEST STEP NAME" accordingly def testRequest = context.testCase.testSteps["TEST STEP NAME"].testRequest def request = testRequest.requestContent; // log.info(request); // create an array of lines of the request, split by newline characters def splitRequest = request.split("\n"); // build a new, empty request def newRequest = ""; // loop through every line in the request that was split for (splitString in splitRequest) { // if we find the line that needs replacing if (splitString.contains("<burglarAlarm>No</burglarAlarm>")) { // find the spacing tabs of the element in question def spacing = splitString.tokenize("<")[0]; // create a new line that exists of the elemnet searched for, a new line character, and appropriate spacing. def newSplit = splitString + '\n' + spacing + "<cancelledForNonPay>1</cancelledForNonPay>" + "\n"; newRequest += newSplit; } else { // if the line is not the one being searched for, append the line as normal, with new line. newRequest += splitString + '\n'; } } log.info(newRequest); // The line below, when uncommented, will overwrite the contents of test step "TEST STEP NAME" //testRequest.setRequestContent(newRequest);
you want.
I believe you want to replace my line here:
def request = testRequest.requestContent;
With:
def request = serialXML;
My scriprt assumed you were using XML from a pre-existing test step. Since that is not the case, you can set it to the value you are parsing from the Excel data source. That should work for what you want.