> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apinizer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Parsing SOAP Message with XmlSlurper and Adding Value to Header Field to Send to Backend

> Parsing SOAP message with Groovy script and adding value to header field to send to backend

## Groovy Script

```groovy theme={null}
import groovy.xml.XmlSlurper
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder

try {
  def namespacePrefix = 'sch'
  def namespaceUri = 'http://kurum.com/ws/some-func-ws/schemas'
  def userName = request_usernameOrKey

  // Parse XML using XmlSlurper and define namespaces
  def rootNode = new XmlSlurper(false, true).parseText(requestBodyTextFromClient).declareNamespace(
    'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
    'sch': 'http://kurum.com/ws/some-func-ws/schemas'
  )

  // Check if Header section exists, create if not
  def headerNode = rootNode.'soapenv:Header'
  if (!headerNode) {
    headerNode = rootNode.appendNode { 'soapenv:Header' {} }
  }

  // Create and add userId element
  def userIdNode = new XmlSlurper(false, true).parseText("<${namespacePrefix}:userId xmlns:${namespacePrefix}='${namespaceUri}'>${userName}</${namespacePrefix}:userId>")
  headerNode.appendNode { mkp.yield userIdNode }

  // Serialize updated XML as string
  def outputXml = XmlUtil.serialize(new StreamingMarkupBuilder().bind {
    mkp.declareNamespace('soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 'sch': 'http://kurum.com/ws/some-func-ws/schemas')
    mkp.yield rootNode
  })

  requestBodyTextToTargetAPI = outputXml
} catch (Exception e) {
  e.printStackTrace()
}
```

## Explanation

This script performs the following operations:

1. **XML Parse**: XML data coming from request body is parsed
2. **Header Check**: Checks if SOAP Header field exists, creates if not
3. **Username Retrieval**: Username information from authentication is retrieved
4. **Adding to Header**: Username information is added to Header field
5. **Sending to Backend**: Updated XML is sent to backend

<Note>
  This script should be run on the request line (Request Policy) because it uses the `requestBodyTextFromClient` and `requestBodyTextToTargetAPI` variables.
</Note>
