Java HTML / XML How to - Get the Declared Entities in a DOM Document








Question

We would like to know how to get the Declared Entities in a DOM Document.

Answer

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
/*from  w w w .j  a v  a 2s.  com*/
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;
import org.xml.sax.InputSource;

public class Main {
  public static String getXMLData() {
    return "your data";
  }

  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(
        new InputSource(new StringReader(getXMLData())));

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