Java
Source Code
Home > Source Code >Java > Basics
 
  Intercepting All Accesses To External Entities During XML SAX Parsing  
 
 
  1. try {

  2.         // Create an XML parser

  3.         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

  4.    

  5.         // Install the entity resolver

  6.         builder.setEntityResolver(new MyResolver());

  7.    

  8.         // Parse the XML file

  9.         Document doc = builder.parse(new File("infilename.xml"));

  10.     } catch (SAXException e) {

  11.         // A parsing error occurred; the xml input is not valid

  12.     } catch (ParserConfigurationException e) {

  13.     } catch (IOException e) {

  14.     }

  15.    

  16.     public class MyResolver implements EntityResolver {

  17.         // This method is called whenever an external entity is accessed

  18.         // for the first time.

  19.         public InputSource resolveEntity (String publicId,String systemId) {

  20.             try {

  21.                 // Wrap the systemId in a URI object to make it convenient

  22.                 // to extract the components of the systemId

  23.                 URI uri = new URI(systemId);

  24.    

  25.                 // Check if external source is a file

  26.                 if ("file".equals(uri.getScheme())) {

  27.                     String filename = uri.getSchemeSpecificPart();

  28.                     return new InputSource(new FileReader(filename));

  29.                 }

  30.             } catch (URISyntaxException e) {

  31.             } catch (IOException e) {

  32.             }

  33.    

  34.             // Returning null causes the caller to try accessing the systemid

  35.             return null;

  36.         }

  37.     }

  38.  

  39. This is the sample input for the example:

  40.     <?xml version="1.0" encoding="UTF-8"?>

  41.     <!DOCTYPE root SYSTEM "System.dtd" [

  42.         <!ENTITY entity1 SYSTEM "External.xml">

  43.         <!ENTITY entity2 SYSTEM "http://hostname.com/my.dtd">

  44.         <!ENTITY % entity3 SYSTEM "More.dtd">

  45.         %entity3;

  46.     ]>

  47.     <root>

  48.          
 
 
Date entered : 5th Apr 2007
Rating : No Rating
Accessed : 4912
Submitted by : javabill
 
0 comments have been posted for this Source Code.View Comments Here
 
Home > Source Code >Java > Basics
Copyright Visualbuilder.com 1999-2006
 
 
 

Warning: Unknown(): write failed: Disk quota exceeded (122) in Unknown on line 0

Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0