2010-09-03 12 views
14

Tengo dificultades para intentar aplicar sangrías a archivos XML usando XMLSerializer.¿Cómo sangrar XML correctamente utilizando XMLSerializer?

He intentado

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", 
         true); 

He intentado añadir \n en FileWriter pero la salida es la \n 's y \t' s en el principio del archivo y no en el lugar correcto. He intentado setPropery con el buen URI etc.

parte del código:

XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance(); 
parserFactory .setNamespaceAware(true); 
XmlSerializer serializer = parserFactory .newSerializer(); 
File xmlFile = new File(PATH + ".xml");   
FileWriter writer = new FileWriter(xmlFile);    
serializer.setOutput(writer); 
//serializer.setProperty(INDENT_URL, INDENT); 
serializer.startDocument("UTF-8", null); 
//serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", 
         true); 
serializer.startTag(null, "bla"); 
writer.append('\n'); 

¿Qué me falta?

Respuesta

4

¿Ha intentado utilizar estas dos propiedades "en combinación" en el serializador?

// indentation as 3 spaces 
serializer.setProperty(
    "http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " "); 
// also set the line separator 
serializer.setProperty(
    "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n"); 
+8

Sí. Lo hice y me dio este error: java.lang.RuntimeException: Unsupported Property: en org.kxml2.io.KXmlSerializer.setProperty (KXmlSerializer.java:260) .... –

+2

Esto no funciona –

+0

@Eduardo Berton: Esta no es la respuesta correcta, no funciona –

3

Esta es una solución en Java, y andriod es compatible con el transformador, por lo que debería funcionar.

// import additional packages 
import java.io.*; 

// import DOM related classes 
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.*; 
import javax.xml.transform.stream.*; 

// write the output file 
try { 
    // create a transformer 
    TransformerFactory transFactory = TransformerFactory.newInstance(); 
    Transformer  transformer = transFactory.newTransformer(); 

    // set some options on the transformer 
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); 
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 

    // get a transformer and supporting classes 
    StringWriter writer = new StringWriter(); 
    StreamResult result = new StreamResult(writer); 
    DOMSource source = new DOMSource(xmlDoc); 

    // transform the xml document into a string 
    transformer.transform(source, result); 

    // open the output file 
    FileWriter outputWriter = new FileWriter(outputFile); 
    outputWriter.write(writer.toString()); 
    outputWriter.close(); 

} catch(javax.xml.transform.TransformerException e) { 
    // do something with this error 
}catch (java.io.IOException ex) { 
    // do something with this error 
} 
+0

:) Solo tengo un buen google foo hoy. El serializador XML es para serializar datos a XML, y el escritor de archivos escribe en un archivo. Por lo tanto, la responsabilidad de formatear algo que pueda leerse en otra clase ya existe :) – JonWillis

+2

Intenté esto, pero sigo obteniendo archivos sin sangría :(Sin embargo, no hay errores – Peterdk

+1

Si puedo agregar algo aquí, asegúrese de ' 'replaceAll (" [\\ s] + "," ")' '' en caso de cadenas. En mi caso, la cadena xml ya tenía '' '\ n''' y no se estaba sangrando. –

35

serializer.setFeature(" http://xmlpull.org/v1/doc/features.html#indent-output ", true); funcionan ahora.

¡No sé si lo estaba poniendo antes de serializer.startDocument(encoding, standalone) o había un error con cosas no relacionadas con la creación .xml!

Gracias chicos!

+0

¿cómo sangrar los comentarios? – accuya

1

Solo quería hacer una nota que Transformer.setOutputProperties(Properties) no parece funcionar para mí (1.6.0_26_b03), pero Transformer.setOutputProperty(String,String) hace perfectamente.
Si tiene un objeto Propiedades, puede tener que iterar y establecer individualmente la propiedad de salida para que funcione.

Cuestiones relacionadas