earl
earl

Reputation: 768

Extract elements from XML and assign to a variable

From this given XML, I would like to extract values for tag and and assign them to a variable. I am using scala.

<soap:Envelope xmlns:wsdlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:iav="http://www.example.com/xxx/yy/ABC_DE_Fghijklmn">
<soap:Body>
<iav:OperationResponse>
<iav:XYZ>AAA</iav:XYZ>
<iav:Code/>
</iav:OperationResponse>
</soap:Body>
</soap:Envelope>

The given XML is assigned to a val resp. I have tried options like:

(resp.get \\"iav:XYZ")

(resp.get \"@iav:XYZ")

(resp.get \\"@iav:XYZ")

(resp.get \"@iav:XYZ")

but they all do not return anything.

How will I achieve this? I will be getting many such set of responses and I would have to do the same extraction and assignment to all sets.

Upvotes: 1

Views: 63

Answers (1)

Vitaly Olegovitch
Vitaly Olegovitch

Reputation: 3547

Here is how to extract it:

import scala.xml.Elem

object StackOverflow {
  def main(args: Array[String]): Unit = {
    val xml = """<soap:Envelope xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:wsdlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:iav="http://www.informatica.com/xxx/yy/ABC_DE_Fghijklmn">
                <soap:Body>
                <iav:OperationResponse>
                <iav:XYZ>AAA</iav:XYZ>
                <iav:Code/>
                </iav:OperationResponse>
                </soap:Body>
                </soap:Envelope>"""
    val xmlElem: Elem = scala.xml.XML.loadString(xml)
    val operationResponse =  xmlElem \\ "OperationResponse"
    val xyz = operationResponse \ "XYZ"
    print( "Operation response is " +  xyz.text)
  }
}

Upvotes: 1

Related Questions