Java/XML/EntityResolver

Материал из Java эксперт
Перейти к: навигация, поиск

Getting the Value of an Entity Reference in a DOM Document

   

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element root = doc.getDocumentElement();
    EntityReference eref = (EntityReference) root.getFirstChild();
    Comment comment = (Comment) eref.getFirstChild(); 
    Element elem = (Element) eref.getFirstChild().getNextSibling(); 
    Text text = (Text) eref.getLastChild(); 
  }
}





implements EntityResolver

   
import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class SimpleEntityResolver implements EntityResolver {
  private static final String USAGE_TERMS_ID = "http://www.n.ru/t.xml";
  private static final String USAGE_TERMS_LOCAL_URI = "C:\\t.xml";
  public InputSource resolveEntity(String publicID, String systemID) throws IOException,
      SAXException {
    if (systemID.equals(USAGE_TERMS_ID)) {
      return new InputSource(USAGE_TERMS_LOCAL_URI);
    }
    return null;
  }
}





Intercepting All Accesses to External Entities During XML SAX Parsing

   
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setEntityResolver(new MyResolver());
    Document doc = builder.parse(new File("infilename.xml"));
  }
}
class MyResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) {
    try {
      URI uri = new URI(systemId);
      if ("file".equals(uri.getScheme())) {
        String filename = uri.getSchemeSpecificPart();
        return new InputSource(new FileReader(filename));
      }
    } catch (Exception e) {
    }
    return null;
  }
}





Preventing Expansion of Entity References While Parsing an XML File

   

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Main {
  public static void main(String[] argv) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    // Prevent expansion of entity references
    factory.setExpandEntityReferences(false);
    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
  }
}





Resolves an entity reference or character reference to its value.

 
/*
 * Copyright Aduna (http://www.aduna-software.ru/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */

public class Utils {
  /**
   * Resolves an entity reference or character reference to its value. 
   *
   * @param entName The "name" of the reference. This is the string between
   * & and ;, e.g. amp, quot, #65 or #x41.
   * @return The value of the supplied reference, or the reference itself
   * if it could not be resolved.
   */
  public static String resolveEntity(String entName) {
    if (entName.startsWith("#")) {
      // character reference
      StringBuilder sb = new StringBuilder();
      if (entName.charAt(1) == "x") {
        // Hex-notation
        sb.append((char)Integer.parseInt(entName.substring(2), 16));
      }
      else {
        // Dec-notation
        sb.append((char)Integer.parseInt(entName.substring(1)));
      }
      return sb.toString();
    }
    else if (entName.equals("apos")) {
      return """;
    }
    else if (entName.equals("quot")) {
      return "\"";
    }
    else if (entName.equals("gt")) {
      return ">";
    }
    else if (entName.equals("lt")) {
      return "<";
    }
    else if (entName.equals("amp")) {
      return "&";
    }
    else {
      return entName;
    }
  }
}





Resolving entities found in source XML during parsing

   
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class Main {
  public static void main(String[] argv) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    SaxHandler handler = new SaxHandler();
    parser.parse("sample.xml", handler);
  }
}
class SaxHandler extends DefaultHandler {
  public InputSource resolveEntity(String publicId, String systemId) {
    if (systemId.equals("http://www.my-company.ru/order-1.0.dtd")) {
      return new InputSource(getClass().getResourceAsStream("order.dtd"));
    } else {
      return null;
    }
  }
  public void startElement(String uri, String localName, String qName, Attributes attrs)
      throws SAXException {
    if (qName.equals("order")) {
    }
  }
  public void error(SAXParseException ex) throws SAXException {
    System.out.println("ERROR: [at " + ex.getLineNumber() + "] " + ex);
  }
  public void fatalError(SAXParseException ex) throws SAXException {
    System.out.println("FATAL_ERROR: [at " + ex.getLineNumber() + "] " + ex);
  }
  public void warning(SAXParseException ex) throws SAXException {
    System.out.println("WARNING: [at " + ex.getLineNumber() + "] " + ex);
  }
}