Saturday 6 August 2011

DOM helper for root element

  

/**
 
 */
//org.ajax4jsf.builder.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This class must read XML file from input stream and can extract body of root
 * element for include into target in generation.
 
 @author shura
 
 */
public class XMLBody {
  private Document xmlDocument;

  private Element rootElement;

  /**
   * Load XML document and parse it into DOM.
   
   @param input
   @throws ParsingException
   */
  public void loadXML(InputStream inputthrows Exception {
    try {
      // Create Document Builder Factory
      DocumentBuilderFactory docFactory = DocumentBuilderFactory
          .newInstance();

      docFactory.setValidating(false);
      // Create Document Builder
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      
      docBuilder.isValidating();
      
      // Disable loading of external Entityes
      docBuilder.setEntityResolver(new EntityResolver() {
        // Dummi resolver - alvays do nothing
        public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
          return new InputSource(new StringReader(""));
        }

      });

      // open and parse XML-file
      xmlDocument = docBuilder.parse(input);

      // Get Root xmlElement
      rootElement = xmlDocument.getDocumentElement();
    catch (Exception e) {
      throw new Exception("Error load XML ", e);
    }

  }

  /**
   * Check name of root element is as expected.
   
   @param name
   @return
   */
  public boolean isRootName(String name) {
    return rootElement.getNodeName().equals(name);
  }

  public String getDoctype() {
    DocumentType doctype = xmlDocument.getDoctype();
    if (null != doctype) {
      return doctype.getName();
    }
    return null;
  }

  public String getPiblicId() {
    DocumentType doctype = xmlDocument.getDoctype();
    if (null != doctype) {
      return doctype.getPublicId();
    }
    return null;
  }

  public String getRootTypeName() {
    return rootElement.getSchemaTypeInfo().getTypeName();
  }

  public String getContent() throws Exception {
    NodeList childNodes = rootElement.getChildNodes();
    return serializeNodes(childNodes);
  }

  private String serializeNodes(NodeList childNodesthrows Exception {
    DocumentFragment fragment = xmlDocument.createDocumentFragment();
    for (int i = 0; i < childNodes.getLength(); i++) {
      fragment.appendChild(childNodes.item(i).cloneNode(true));
    }
    try {
      TransformerFactory transformerFactory = TransformerFactory
          .newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty("omit-xml-declaration""yes");
      StringWriter out = new StringWriter();
      StreamResult result = new StreamResult(out);
      transformer.transform(new DOMSource(fragment), result);
      return out.toString();

    catch (Exception e) {
      throw new Exception(e);
    }
  }
  
  public String getContent(String xpaththrows Exception{
    XPath path = XPathFactory.newInstance().newXPath();
    NodeList childNodes;
    try {
      childNodes = (NodeListpath.evaluate(xpath, xmlDocument,XPathConstants.NODESET);
    catch (XPathExpressionException e) {
      throw new Exception("Error evaluate xpath",e);
    }
    return serializeNodes(childNodes);
  }
}

   
    
  

No comments:

Post a Comment