good afternoon I have the following code to read an xml file
import xml.etree.ElementTree as ET
archivo_xml = ET.parse('files/prodinfo_ES.xml')
raiz = archivo_xml.getroot()
archivo_xml = ET.parse('files/prodinfo_ES.xml')
raiz = archivo_xml.getroot()
prueba=['AR1249','AR1253']
for p in prueba:
for node in raiz.iter('PRODUCT'):
ID = node.findtext('PRODUCT_BASE_NUMBER')
if ID == p:
caja2 = node.findtext('PACKAGING_CARTON')
print(caja2)
My goal is to obtain the values of PACKAGING_CARTON for a respective calculation. My question is, how can I access these values? the xml file is as follows
<?xml version="1.0" encoding="utf-8"?>
<PRODUCTINFORMATION>
<SUPPLIER>Mid Ocean Brands</SUPPLIER>
<DATE>20220209</DATE>
<TIME>03:00:03</TIME>
<LANGUAGE>ES</LANGUAGE>
<PRODUCTS>
<PRODUCT>
<PRODUCT_BASE_NUMBER>AR1249</PRODUCT_BASE_NUMBER>
<PRODUCT_ID>10134325</PRODUCT_ID>
<PACKAGING_CARTON>
<LENGTH>0,575</LENGTH>
<WIDTH>0,275</WIDTH>
<HEIGHT>0,215</HEIGHT>
<SIZE_UNIT>M</SIZE_UNIT>
<WEIGHT>13,800</WEIGHT>
<WEIGHT_UNIT>KG</WEIGHT_UNIT>
<VOLUME>0,034</VOLUME>
<VOLUME_UNIT>M3</VOLUME_UNIT>
<INNER_CARTON_QUANTITY>10</INNER_CARTON_QUANTITY>
<CARTON_QUANTITY>100</CARTON_QUANTITY>
</PACKAGING_CARTON>
</PRODUCT>
the result when I print box is 2 empty lines I hope you can help me
option two
import xml.etree.ElementTree as ET
import xmltodict
import json
def load_json(path: str) -> dict:
if path.endswith(".json"):
print(f"> Loading JSON from '{path}'")
with open(path, mode="r") as open_file:
content = open_file.read()
return json.loads(content)
elif path.endswith(".xml"):
print(f"> Loading XML as JSON from '{path}'")
xml = ET.tostring(ET.parse(path).getroot())
return xmltodict.parse(xml, attr_prefix="@", cdata_key="#text", dict_constructor=dict)
print(f"> Loading failed for '{path}'")
return {}
path = "files/prodinfo_ES.xml"
data = load_json(path)
for key in data:
print(key,':',data[key])
but I don't know how to access only the value of PACKAGING_CARTON
I use xmltodict . It allows you to use the content of the xml as if it were a dictionary.