-1
I am reading thousands of XML files with python. The problem is, there is not always the field in all files.
resumo_cv = root.find("DADOS-GERAIS").find("RESUMO-CV").get("TEXTO-RESUMO-CV-RH")
resumo_cv_ingles = root.find("DADOS-GERAIS").find("RESUMO-CV").get("TEXTO-RESUMO-CV-RH-EN")
palavras_chave_mestrado = root.find("DADOS-GERAIS").find("FORMACAO-ACADEMICA-TITULACAO").find("MESTRADO").find("PALAVRAS-CHAVE")
list_palavras_chave_mestrado = ""
if palavras_chave_mestrado is not None:
for palavra, valor in palavras_chave_mestrado.items():
if valor is not None and valor != "":
list_palavras_chave_mestrado =
In case, the above code would look like this:
dados_gerais = root.find("DADOS-GERAIS")
if dados_gerais is not None:
resumo_cv = dados_gerais.find("RESUMO-CV")
if resumo_cv is not None:
texto_resumo_cv = resumo_cv.get("TEXTO-RESUMO-CV-RH")
if texto_resumo_cv is None:
texto_resumo_cv = ''
texto-resumo_cv_ingles = resumo_cv.get("TEXTO-RESUMO-CV-RH-EN")
if resumo_cv_ingles is None:
texto_resumo_cv_ingles = ''
That is, a check for each field (find) and (get). Not to mention, some XML fields have to go through lists... Is there any optimized way using Try-cacth or anything else? Hahah obg.
And these methods throw some exception in the cases cited? If they do not launch, it is useless to use
try/catch
.– Woss
Only both return None if not found.
– thiagoheron