2011-11-24 11 views
8

Sto usando il collegamento this per generare file XML usando DOM. Dice che "il parser Xerces è in bundle con la distribuzione JDK 1.5. Non è necessario scaricare il parser separatamente."Serialize DOM to FileOutputStream usando Xerces

Tuttavia, quando scrivo la seguente riga nel mio Eclipse Helios, viene restituito un errore in fase di compilazione anche se nel sistema ho Java 1.6.

import org.apache.xml.serialize.XMLSerializer; 

Perché è così?

risposta

26

Xerces è effettivamente fornito in bundle con JDK ma è necessario utilizzarlo con l'API JAXP sotto javax.xml.parsers. Controlla l'output del programma qui sotto.

Inoltre, per serializzare un XML Document, è necessario utilizzare il caricamento e il salvataggio di DOM Level 3 (presente nel JDK) o una trasformazione XSLT senza alcun foglio di stile (trasformazione dell'identità). Il resto dipende da un'implementazione specifica. Xerces XMLSerializer è obsoleto:

Obsoleto. Questa classe è stata deprecata in Xerces 2.9.0. Si raccomanda che le nuove applicazioni utilizzino il LSSerializer DOM Level 3 o l'API di trasformazione JAXP per XML (TrAX) per serializzare XML. Vedi la documentazione di Xerces per maggiori informazioni.

Ecco un esempio di serializzazione con il livello DOM 3:

import org.w3c.dom.*; 
import org.w3c.dom.bootstrap.DOMImplementationRegistry; 
import org.w3c.dom.ls.*; 

public class DOMExample3 { 

    public static void main(String[] args) throws Exception { 
     DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();  
     DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0"); 
     if (impl == null) { 
      System.out.println("No DOMImplementation found !"); 
      System.exit(0); 
     } 

     System.out.printf("DOMImplementationLS: %s\n", impl.getClass().getName()); 

     LSParser parser = impl.createLSParser(
       DOMImplementationLS.MODE_SYNCHRONOUS, 
       "http://www.w3.org/TR/REC-xml"); 
     // http://www.w3.org/2001/XMLSchema 
     System.out.printf("LSParser: %s\n", parser.getClass().getName()); 

     if (args.length == 0) { 
      System.exit(0); 
     } 

     Document doc = parser.parseURI(args[0]); 

     LSSerializer serializer = impl.createLSSerializer(); 
     LSOutput output = impl.createLSOutput(); 
     output.setEncoding("UTF-8"); 
     output.setByteStream(System.out); 
     serializer.write(doc, output); 
     System.out.println(); 
    } 
} 

Ecco un esempio con una trasformazione di identità:

import org.w3c.dom.Document; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.transform.OutputKeys; 
import javax.xml.transform.Result; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 

public class DOMExample2 { 
    public static void main(String[] args) throws Exception { 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder parser = factory.newDocumentBuilder(); 

     System.out.println("Parsing XML document..."); 
     Document doc; 
     doc = parser.parse(args[0]); 

     // Xerces Java 2 

     /* Deprecated. This class was deprecated in Xerces 2.9.0. 
     * It is recommended that new applications use the DOM Level 3 
     * LSSerializer or JAXP's Transformation API for XML (TrAX) 
     * for serializing XML and HTML. 
     * See the Xerces documentation for more information. 
     */ 
     /* 
     System.out.println("XERCES: Displaying XML document..."); 
     OutputFormat of = new OutputFormat(doc, "ISO-8859-1", true); 
     PrintWriter pw = new PrintWriter(System.out); 
     BaseMarkupSerializer bms = new XMLSerializer(pw, of); 
     bms.serialize(doc); 
*/ 
     // JAXP 

     System.out.println("JAXP: Displaying XML document..."); 
     TransformerFactory transFactory = TransformerFactory.newInstance(); 
     System.out.println(transFactory.getClass().getName()); 
     //transFactory.setAttribute("indent-number", 2); 
     Transformer idTransform = transFactory.newTransformer(); 
     idTransform.setOutputProperty(OutputKeys.METHOD, "xml"); 
     idTransform.setOutputProperty(OutputKeys.INDENT,"yes"); 
     // Apache default indentation is 0 
     idTransform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");     
     Source input = new DOMSource(doc); 
     Result output = new StreamResult(System.out); 
     idTransform.transform(input, output); 
    } 
} 
+0

Grazie. Questo ha aiutato :) – whitehat

+0

Se pensi che possa essere considerata una risposta, puoi segnalarla? – lkuty

+1

Ho aumentato il conteggio facendo clic su "Questa risposta è utile" :) – whitehat

1

Sarà in, IIRC, com.sun.org.apache.xml.serialize.XMLSerializer. Tuttavia, quelli sono classi private e suscettibili di cambiamenti in qualsiasi momento. Suggerisco invece di utilizzare le API pubbliche standard (javax.* e amici). (Utilizza l'API di trasformazione senza XSLT.)