Monday, May 24, 2021
Phyton - parse XML from string or file with namespaces with ElementTree
Here is sample how to parse XML in Phyton. XML has namespaces.
----------------
import xml.etree.ElementTree as ET
xml = '<?xml version="1.0" encoding="UTF-8"?><application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" version="6"> <display-name>ORDS-EAR</display-name> <module> <web> <web-uri>ORDS-WAS-19.1.0.092.1545.war</web-uri> <context-root>/ords</context-root> </web> </module></application>';
tree = ET.ElementTree(ET.fromstring(xml))
#tree = ET.ElementTree(ET.from('application.xml'))
root = tree.getroot()
ns = {'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'javaee': 'http://java.sun.com/xml/ns/javaee',
'schemaLocation': 'http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd'
}
war_name = '';
for modvar in root.findall('javaee:module', ns):
for webvar in modvar.findall('javaee:web', ns):
urivar = webvar.find('javaee:web-uri', ns);
war_name = urivar.text;
print (war_name);
----------------
