Python Forum

Full Version: xml file editing with lxml.etree
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody

I would like to ask for some help.

I face a problem when trying to edit an xml file with python and lxml.etree
When trying to edit the data of the numeroCarteira tag, it does not edit properly.

Can anyone help me?
this is the code
import lxml.etree as ET

# Carregar o arquivo XML
tree = ET.parse('exemplo.xml')
root = tree.getroot()

# Definir o namespace
namespace = {'ns0': 'http://www.ans.gov.br/padroes/tiss/schemas'}

# Navegar e fazer alterações no XML
for elemento in root.xpath('//ns0:elemento', namespaces=namespace):
    numero_carteira = elemento.xpath('.//ns0:numeroCarteira', namespaces=namespace)[0].text

    # Verificar o número de caracteres
    if len(numero_carteira) < 6:
        numero_carteira = '00' + numero_carteira

    # Atualizar o valor do elemento
    elemento.xpath('.//ns0:numeroCarteira', namespaces=namespace)[0].text = numero_carteira

# Salvar as alterações de volta no arquivo
tree.write('exemplo.xml', encoding='UTF-8', xml_declaration=True)
Post sample of exemplo.xml and explain output wanted.
Sorry for the delay guys.

I was able to fix my code by changing the xml navigation lines.

''' CORRIGIR CONSULTA  ''' 

import xml.etree.ElementTree as ET
import os

# Obter a lista de nomes de arquivo XML no diretório
diretorio = 'C:/Users/flavio.bueno/Projetos_Python/XML'
arquivos_xml = [arquivo for arquivo in os.listdir(diretorio) if arquivo.endswith('.xml')]


# Processar cada arquivo XML
for arquivo in arquivos_xml:
    # Carregar o arquivo XML
    caminho_arquivo = os.path.join(diretorio, arquivo)
    tree = ET.parse(caminho_arquivo)
    root = tree.getroot()

    # Definir o namespace
    namespace = {'ans': 'http://www.ans.gov.br/padroes/tiss/schemas'}    
    
    # Navegar e fazer alterações no XML
    for elemento in root.findall('.//ans:guiaConsulta', namespace):
        numero_carteira = elemento.find('.//ans:numeroCarteira', namespace)

        # Verificar o número de caracteres
        if len(numero_carteira.text) < 6:
            numero_carteira.text = '00' + numero_carteira.text
        
        elif len(numero_carteira.text) < 7:
            numero_carteira.text = '0' + numero_carteira.text  
    
    # Salvar as alterações de volta no arquivo
    tree.write(caminho_arquivo, encoding='UTF-8', xml_declaration=True)