Visualizzazione dei risultati da 1 a 5 su 5
  1. #1

    Java e XML: indentazione con JAXP

    Ciao a tutti.
    Ecco il mio quesito: dato il seguente xml, come faccio a formattarlo in maniera tale da ottenere una corretta indentazione?

    codice:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <LIBRERIA>
    <LIBRO id="1">
    <AUTORE>prova</AUTORE>
    <TITOLO>prova</TITOLO>
    <ANNO>2012</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>gio</AUTORE>
    <TITOLO>gio</TITOLO>
    <ANNO>2</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>p</AUTORE>
    <TITOLO>p</TITOLO>
    <ANNO>loi</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>9</AUTORE>
    <TITOLO>00</TITOLO>
    <ANNO>yy</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>kk</AUTORE>
    <TITOLO>jhfjgv</TITOLO>
    <ANNO>867</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>oo</AUTORE>
    <TITOLO>kk</TITOLO>
    <ANNO>9898</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>OTTO</AUTORE>
    <TITOLO>OTTO</TITOLO>
    <ANNO>1234</ANNO>
    </LIBRO>
    <LIBRO>
    <AUTORE>cxvcx</AUTORE>
    <TITOLO>kjghkg</TITOLO>
    <ANNO>9</ANNO>
    </LIBRO>
    </LIBRERIA>
    Premetto che ho tentato la seguente soluzione, ma senza alcun risultato:

    codice:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    	
    Document document = builder.parse(new File("libri.xml"));
    
    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setAttribute("indent-number", new Integer(2));
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    			
    DOMSource source = new DOMSource(document);
    			
    //Stampol'output sul file xml
    StreamResult result1 = new StreamResult(new File("libri.xml"));
    transformer.transform(source, result1);
    			
    //Stampo l'output sulla console
    StreamResult result2 = new StreamResult(System.out);
    transformer.transform(source, result2);
    Grazie a tutti x l'aiuto...

  2. #2
    assolutamente nessuna idea?

  3. #3
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,320
    Ho effettuato delle prove ed ho verificato che quel metodo funziona se l'XML di partenza è in una sola riga. Evidentemente per il Transformer quello non è un documento normalizzato e non riesce a formattarlo come si deve (credo che la causa sia il newLine a fine di ogni riga)

    Se il tuo documento è in quella forma, credo dovrai lavorarlo a mano, costruendo una classe che effettui l'indentazione.

    Sto effettuando anche altre prove per vedere se si riesce in qualche modo a normalizzare il file (i metodi normalize() e normalizeDocument() non hanno effetto, in questo senso).


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  4. #4
    grazie per la risposta.
    hai ragione, non mi ero accorto che se l'xml si trova in una sola riga funziona tutto perfettamente...
    credi esista un metodo per "appiattire" di volta in volta il contenuto su un'unica riga per poi parsarlo da zero ottenendo la giusta formattazione?
    tnx

  5. #5
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Per appiattire mi sa che resta di leggere tutto il file e crearne uno nuovo d'appoggio (orribile e scomodo, però si risolve in 4 righe):
    codice:
    import java.io.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.Document;
    /**
     *
     * @author Andrea
     */
    public class Esercizio37 {
        
        public static void main (String[] args) {
            File base_path = new File ("C:/Users/Andrea/Desktop");
            File origin = new File(base_path, "xml.xml");
            File dest = new File(base_path, "dest.xml");
            try {
                FileWriter fw = new FileWriter(dest);
                BufferedReader br = new BufferedReader(new FileReader(origin));
                String line;
                while ((line = br.readLine()) != null) {
                    fw.write(line);
                }
                fw.flush();
                fw.close();
                
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                
                Document document = builder.parse(dest);
                
                TransformerFactory tFactory = TransformerFactory.newInstance();
                tFactory.setAttribute("indent-number", new Integer(2));
                Transformer transformer = tFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                
                DOMSource source = new DOMSource(document);
                
                //Stampol'output sul file xml
                StreamResult result1 = new StreamResult(dest);
                transformer.transform(source, result1);
                
                //Stampo l'output sulla console
                StreamResult result2 = new StreamResult(System.out);
                transformer.transform(source, result2);
            }        
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.