AnsweredAssumed Answered

Extracting elements from XML using Xpath

Question asked by rohit_tiwari on Aug 3, 2018

Hi,

 

I need to extract last and second last occurrence of a repeating node from a XML. can you please help in writing groovy script using xpath. Completely noob at xpath, please correct for any syntax error. Here is the script:

 

"comtec-mobile-communication/message-out/actions/stop[last()-1 and last()]" --this statement works in online xpath editor

 

// Loop through the Process Documents
for ( int i = 0; i < dataContext.getDataCount(); i++ ) {

InputStream is = dataContext.getStream(i);
Properties props = dataContext.getProperties(i);

// Build XML Document
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(is);

XPath x;
x = XPath.newInstance("//comtec-mobile-communication");

eleMyElement = comtec-mobile-communication/message-out/actions/stop[last()-1 and last()];

//Output
XMLOutputter outputter = new XMLOutputter();
is = new ByteArrayInputStream(outputter.outputString(doc).getBytes("UTF-8"));

dataContext.storeStream(is, props);

}

 

Any other idea will also be appreciated.

 

Thanks,

Rohit

Outcomes