Formatear Un Fichero Xml Y Reescribirlo Con El Formateo

Formatear Un Fichero Xml Y Reescribirlo Con El Formateo
Article
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 - Profile PM  
gambafeliz [ Tuesday, 14 July 2020, 20:40 ]


Formatear Un Fichero Xml Y Reescribirlo Con El Formateo
Comments
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



 
jguardon - Profile PM  
jguardon [ Wednesday, 15 July 2020, 16:05 ]
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 - Profile PM  
gambafeliz [ Wednesday, 15 July 2020, 22:43 ]
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 - Profile PM  
gambafeliz [ Wednesday, 15 July 2020, 23:15 ]
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 - Profile PM  
gambafeliz [ Thursday, 16 July 2020, 09:18 ]
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



 
jguardon - Profile PM  
jguardon [ Thursday, 16 July 2020, 16:54 ]
Display posts from previous:    
Post new topic  Reply to topic  Page 1 of 1
 
 

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


 


   

This is a "Lo-Fi" version of our main content. To view the full version with more information, formatting and images, please click here.

Powered by Icy Phoenix based on phpBB
Design by DiDiDaDo

Generation Time: 0.1721s (PHP: -47% SQL: 147%)
SQL queries: 24 - Debug Off - GZIP Enabled