Sample Xpath in Python

sample xpath in python

XPath (XML Path Language) adalah bahasa kueri untuk memilih bagian – bagian (nodes) dari sebuah dokumen XML. XPath juga dapat digunakan untuk menghitung nilai (contoh : string, angka atau boolean) dari isi dari sebuah dokumen XML. XPath distandarisasi oleh World Wide Web Consortium (W3C)

berikut ini contoh penggunaan xpath pada python

buat file xml terlebih dahulu misal kita namakan cancel_response.xml

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
	<SOAP-ENV:Envelope
	xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/”
	xmlns:xsd=”http://www.w3.org/2001/XMLSchema”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xmlns:SOAP-ENC=”http://schemas.xmlsoap.org/soap/encoding/”
	xmlns:tns=”urn:webservice”>
		<SOAP-ENV:Body>
			<ns1:WsCancelPNRResponse xmlns:ns1=”urn:sj_service”>
				<return xsi:type=”tns:respWsCancelPNR”>
					<Username xsi:type=”xsd:string”>xy</Username>
					<BookingCode xsi:type=”xsd:string”>QTGPDF</BookingCode>
					<ErrorCode xsi:type=”xsd:string”>CANCEL0005</ErrorCode>
					<ErrorMessage xsi:type=”xsd:string”>Invalid PNR status.</ErrorMessage>
				</return>
			</ns1:WsCancelPNRResponse>	
		</SOAP-ENV:Body>
	</SOAP-ENV:Envelope>

 

buat file untuk parse XPath misal parse.py

 

import requests
import json
from lxml import etree
from lxml.builder import ElementMaker
from lxml.objectify import fromstring
from io import StringIO, BytesIO
from collections import OrderedDict
 
def process_response():
 
    response = open('cancel_response.xml').read()
    response_namespaces={
        'e' : 'http://schemas.xmlsoap.org/soap/envelope/',
        'ns1':'urn:sj_service'
    }
 
    tree = etree.fromstring(response.encode('utf-8'))
 
    x_response = tree.xpath('//e:Body/ns1:WsCancelPNRResponse/return',namespaces=response_namespaces)
 
    message = x_response[0].xpath('ErrorMessage/text()')[0]
    booking_code = x_response[0].xpath('BookingCode/text()')[0]
 
    response_message = OrderedDict()
    response_message['booking_code'] = booking_code
    response_message['message'] = message
    json_response = json.dumps(response_message)
 
    print(json_response)

 

Good Luck … !

mm

Alfin F

Technopreneur , Developer, Advisor

More Posts

Follow Me:
TwitterLinkedIn