groovy : xpath evalution ; frequently used step

 



<?xml version="1.0"?>
<root>
    <person id="1">
        <name>John</name>
        <age>30</age>
    </person>
    <person id="2">
        <name>Jane</name>
        <age>25</age>
    </person>
</root>


import com.sap.gateway.ip.core.customdev.util.Message
import groovy.util.XmlSlurper
import java.util.HashMap;
import java.util.*;

def Message processData(Message message) {
    try {
        def body = message.getBody()
    def xml = new XmlParser().parse(body);

        // Check if the root node exists
        if (xml instanceof groovy.util.Node) {
            println("Root node: ${xml.name()}")

            // Iterate through child nodes
            xml.depthFirst().each { node ->
                if (node instanceof groovy.util.Node) {
                    println("Node name: ${node.name()}")

  if(node.name()=="age" && node.text()=="25") println("Node name  age with value 25: ${node.name()}")

 if(node.parent()=="person" && node.text()=="25") println("Node parent  person with value 25: ${node.name()}")                    // Check for attributes
                    node.attributes().each { attr ->
                        println("Attribute '${attr.key}' exists with value: ${attr.value}")
                    }

                    // Check for elements
                    println("Element text: ${node.text()}")
                }
            }
        } else {
            println("Root node does not exist.")
        }
    } catch (Exception e) {
        println("Error processing XML: ${e.message}")
    }

    return message
}



---------
checking parent node:



-------------
gtp code
import groovy.util.XmlSlurper

// Sample XML data
def xmlData = '''
<root>
    <person id="1">
        <name>John</name>
        <age>30</age>
    </person>
    <person id="2">
        <name>Jane</name>
        <age>25</age>
    </person>
</root>
'''

// Parse the XML data using XmlSlurper
def xml = new XmlSlurper().parseText(xmlData)

// Define an XPath expression to access a specific value
def xpathExpression = "//person[@id='1']/age"

// Use the evaluate method to extract the value based on the XPath expression
def extractedValue = xml.'**'.find { node ->
    node.name() == 'age' && node.parent().@id.text() == '1'
}.text()

// Define the expected value for validation
def expectedValue = '30'

// Perform the validation
if (extractedValue == expectedValue) {
    println("Validation passed: Extracted value '$extractedValue' matches the expected value '$expectedValue'.")
} else {
    println("Validation failed: Extracted value '$extractedValue' does not match the expected value '$expectedValue'.")
}

Popular posts from this blog

pss book : శ్రీకృష్ణుడు దేవుడా, భగవంతుడా completed , second review needed. 26th April 2024

pss book: గురు ప్రార్థనామంజరి . completed 21st july 2024

pss book: కధల జ్ఞానము read review pending. 25th june 2024