2015-02-19 17 views
5

Ho creato un jar contenente un file DTD. Voglio utilizzare questo jar in un'applicazione esterna, in cui il file DTD verrà utilizzato per un file XML.dove posizionare DTD all'interno di un pacchetto

La mia domanda è come posso rendere accessibile il mio file dtd (che si trova nel file .jar) da xml?

Come facciamo in altri file di configurazione diciamo puntoni di sospensione ecc., Definiamo DTD in xml che sono inclusi nei file .jar. Voglio fare lo stesso nel mio file jar, ma non sono in grado di capire la strada, per favore aiuto.

risposta

3

È possibile implementare un org.xml.sax.EntityResolver

public class MyResolver implements EntityResolver { 

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 
     if (systemId.contains("my.dtd")) { 
      InputStream myDtdRes = getClass().getResourceAsStream("/com/yourcompany/my.dtd"); 
      return new InputSource(myDtdRes); 
     } else { 
      return null; 
     } 
    } 
} 

e utilizzarlo con il vostro DocumentBuilder.setEntityResolver()

DocumentBuilder docBuilder = ... 
docBuilder.setEntityResolver(new MyResolver()); 
1

È necessario creare una classe EntityResolver per risolvere l'ID pubblico o di sistema del DTD per la copia del il DTD che stai posizionando nel JAR.

DocumentBuilderFactory factory = xmlFactories.newDocumentBuilderFactory(); 
factory.setNamespaceAware(true); 
factory.setValidating(false); 
DocumentBuilder documentBuilder = factory.newDocumentBuilder(); 
documentBuilder.setEntityResolver(new EntityManager()); 

...... 

public class EntityManager implements EntityResolver { 
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 
     /* code to check the public or system ID and return contents of DTD */ 
    } 

} 
2

Ecco l'frammenti di codice per voi ...

Aggiungi DTD alle JAR

classe

Usa Resolver per DTD per posizionare DTD al vostro vaso

DocumentBuilderFactory myFactory = xmlFactories.newDocumentBuilderFactory(); 
    myFactory.setNamespaceAware(true); 
    myFactory.setValidating(false); 
    DocumentBuilder db = myFactory.newDocumentBuilder(); 
    db.setEntityResolver(new EntityManager()); 



    public class EntityManager implements EntityResolver 
    { 
     public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 
      /* returns contents of DTD */ 
     } 

    } 

Carica DTD da JAR

InputStream ins = this.getClass().getResourceAsStream("project/mypackage/File.dtd"); 

Quindi, ora avete InputStream e si può usare come volete

Spero che ti aiuta :)

Problemi correlati