Home    Forum    Search    FAQ    Register    Log in


Post new topic  Reply to topic 
Page 1 of 1
 
 
Formatear Un Fichero Xml Y Reescribirlo Con El Formateo
Author Message
Reply with quote   Download Post  
Post Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
Hola

Estoy intentando formatear un fichero XML que no esta bien formateado.

Mi intensión es:

1. Formatear el fichero.xml
2. Reescribirlo sobre si mismo pero con el formateado.

Gracias.

Nota: Parto de una clase llamada myglobal.py:
import xml.etree.cElementTree as ET

class Global:
        gRoot = ET.parse('datos.xml').getroot()
 


y la uso en mi programa python:

import myglobal
 



 
gambafeliz - View user's profileSend private message 
Back to topPage bottom
Reply with quote   Download Post  
Post Re: Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
Quizás esto pueda ayudarte, una vez hayas creado el fichero en memoria (xmlstr)


from xml.dom import minidom

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
with open("datos.xml", "w") as f:
    f.write(xmlstr)
 



Saludos
 




===================
Jesús Guardón

Por favor, usemos el corrector ortográfico antes de pulsar el botón "Enviar".

"uo ǝs ʇɐu pıɟıɔıן ɐdɹǝupǝɹ ɐ dɹoƃɹɐɯɐɹ, soןo ɥɐʎ bnǝ dɹodouǝɹsǝןo"
 
jguardon - View user's profileSend private message 
Back to topPage bottom
Reply with quote   Download Post  
Post Re: Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
jguardon escribió:  
Quizás esto pueda ayudarte, una vez hayas creado el fichero en memoria (xmlstr)


from xml.dom import minidom

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
with open("datos.xml", "w") as f:
    f.write(xmlstr)
 



Saludos


Gracias jguardon.

Lo que pasa es que este código lo que hace es borrar mi archivo.xml, esto es lo que queda dentro:

<?xml version="1.0" ?>
<root/>

Algo no funciona o yo no se interpretar "root" el que me has puesto.

Por otra parte permiteme que os haga una nueva duda aquí. Ahora he probado desde la consola esto (y funciona muy bien):

cat /home/miusuario/Python/datos.xml | python -c 'import sys;import xml.dom.minidom;s=sys.stdin.read();print xml.dom.minidom.parseString(s).toprettyxml().encode('utf-8')' > /home/miusuario/Python/datos_tmp.xml

Pero como ya os he dicho, funciona muy bien directamente desde la consola pero no me funciona desde python, ¿que código debo escribir para que funcione, perfectamente bajo python, alguien me dice como hacerlo?.

Gracias.
 



 
Last edited by gambafeliz on Wednesday, 15 July 2020, 22:45; edited 2 times in total 
gambafeliz - View user's profileSend private message 
Back to topPage bottom
Reply with quote   Download Post  
Post Re: Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
gambafeliz escribió:  
Ahora he probado desde la consola esto (y funciona muy bien):

cat /home/miusuario/Python/datos.xml | python -c 'import sys;import xml.dom.minidom;s=sys.stdin.read();print xml.dom.minidom.parseString(s).toprettyxml().encode('utf-8')' > /home/miusuario/Python/datos_tmp.xml

Pero como ya os he dicho, funciona muy bien directamente desde la consola pero no me funciona desde python, ¿que código debo escribir para que funcione, perfectamente bajo python, alguien me dice como hacerlo?


Así lo he solucionado aunque no estoy del todo satisfecho. Digamos que esta regular formateado.
Código: [Descargar] [Ocultar]
  1.     codificacion = '"utf-8"' 
  2.     comandos = "'import sys;import xml.dom.minidom;s=sys.stdin.read();print xml.dom.minidom.parseString(s).toprettyxml().encode("+codificacion+")'" 
  3.     os.system("cat /home/miusuario/Python/datos.xml | python -c "+comandos+" > /home/miusuario/Python/datos_tmp.xml")  
  4.  

 



 
gambafeliz - View user's profileSend private message 
Back to topPage bottom
Reply with quote   Download Post  
Post Re: Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
jguardon escribió:  
Quizás esto pueda ayudarte, una vez hayas creado el fichero en memoria (xmlstr)


from xml.dom import minidom

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
with open("datos.xml", "w") as f:
    f.write(xmlstr)
 



Saludos


Gracias de nuevo jguardon, he seguido estudiando tu código y si funciona pero existía un problema de creación de lineas en blanco tras cada linea xml y con tu código y algo más esto es lo que funciona superbien.

def formatearXML():
    root = myglobal.Global.gRoot
    xmlstr = xml.dom.minidom.parseString(myglobal.ET.tostring(root, 'utf-8')).toprettyxml()
    xmlstr = os.linesep.join([s for s in xmlstr.splitlines() if s.strip()]) 'esta linea limpia las lineas en blanco
    with open("datos.xml", "w") as f:
        f.write(xmlstr)    
        f.close() '
aquí cierro el open pero sino se pone no pasa nada
 

 



 
gambafeliz - View user's profileSend private message 
Back to topPage bottom
Reply with quote   Download Post  
Post Re: Formatear Un Fichero Xml Y Reescribirlo Con El Formateo 
 
Me alegro mucho. Es muy raro que algo no se pueda realizar en Python, junto con los miles de librerías disponibles conforman un lenguaje muy potente.

Saludos
 




===================
Jesús Guardón

Por favor, usemos el corrector ortográfico antes de pulsar el botón "Enviar".

"uo ǝs ʇɐu pıɟıɔıן ɐdɹǝupǝɹ ɐ dɹoƃɹɐɯɐɹ, soןo ɥɐʎ bnǝ dɹodouǝɹsǝןo"
 
jguardon - View user's profileSend private message 
Back to topPage bottom
Display posts from previous:    
 
HideSimilar Topics
Topic Author Forum Replies Last Post
No new posts Error Al Abrir Fichero BrunoIV General 3 Friday, 20 May 2011, 14:46 View latest post
Guest
No new posts Formatear La Salida De Una Consulta Sql alberto_moyano Bases de Datos 0 Wednesday, 15 June 2016, 00:36 View latest post
alberto_moyano
No new posts ¿Como Formateo La Siguiente Fecha? gambafeliz General 9 Monday, 26 August 2019, 08:35 View latest post
Shell
No new posts Formatear El Código De Gambas Shell General 7 Wednesday, 13 May 2020, 23:05 View latest post
Shell
 

Post new topic  Reply to topic  Page 1 of 1
 

Users browsing this topic: 0 Registered, 0 Hidden and 1 Guest
Registered Users: None


 
Permissions List
You cannot post new topics
You cannot reply to topics
You cannot edit your posts
You cannot delete your posts
You cannot vote in polls
You cannot attach files
You can download files
You cannot post calendar events



  

 

cron