Getting the Declared Entities in a DOM Document : DOM Parser « XML « Java Tutorial






import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Entity;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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"));

    Map entityValues = new HashMap();
    getEntityValues(doc, entityValues);

    NamedNodeMap entities = doc.getDoctype().getEntities();
    for (int i = 0; i < entities.getLength(); i++) {
      Entity entity = (Entity) entities.item(i);
      System.out.println(entity);
      String entityName = entity.getNodeName();
      System.out.println(entityName);
      String entityPublicId = entity.getPublicId();
      System.out.println(entityPublicId);
      String entitySystemId = entity.getSystemId();
      System.out.println(entitySystemId);
      Node entityValue = (Node) entityValues.get(entityName);
      System.out.println(entityValue);
    }
  }

  public static void getEntityValues(Node node, Map map) {
    if (node instanceof EntityReference) {
      map.put(node.getNodeName(), node);
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      getEntityValues(list.item(i), map);
    }
  }
}








33.2.DOM Parser
33.2.1.DOM Objects That Make Up the Parse Tree
33.2.2.A DOM Error Checker: Using DOM for Syntax Checking
33.2.3.A DOM Parse Tree Lister
33.2.4.Listing the Contents of Parse Tree Nodes: Using the DOM Parser to Extract XML Document Data
33.2.5.Ignorable Whitespace and Element Content
33.2.6.Remove the element from parent
33.2.7.Visiting All the Elements in a DOM Document
33.2.8.Getting the Root Element in a DOM Document
33.2.9.Getting a Node Relative to Another Node in a DOM Document
33.2.10.Getting the Notations in a DOM Document
33.2.11.Getting the Declared Entities in a DOM Document
33.2.12.Getting the Value of an Entity Reference in a DOM Document
33.2.13.Getting a DOM Element by Id
33.2.14.Converting an XML Fragment into a DOM Fragment
33.2.15.Parse an XML string: Using DOM and a StringReader.
33.2.16.Use DOM L3 DOMBuilder, DOMBuilderFilter DOMWriter and other DOM L3 functionality to preparse, revalidate and safe document.
33.2.17.Read XML as DOM
33.2.18.Create DOM Document out of string
33.2.19.Source To InputSource