Example usage for javax.xml.parsers DocumentBuilder getDOMImplementation

List of usage examples for javax.xml.parsers DocumentBuilder getDOMImplementation

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder getDOMImplementation.

Prototype


public abstract DOMImplementation getDOMImplementation();

Source Link

Document

Obtain an instance of a DOMImplementation object.

Usage

From source file:Main.java

/**
 * Returns a namespaced root element of a document
 * Useful to create a namespace holder element
 * @param namespace/*from  w ww. ja v  a2s  .  c  o m*/
 * @return the root Element
 */
public static Element getRootElement(String elementName, String namespace, String prefix)
        throws TransformerException {
    Element rootNS = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Document namespaceHolder = impl.createDocument(namespace,
                (prefix == null ? "" : prefix + ":") + elementName, null);
        rootNS = namespaceHolder.getDocumentElement();
        rootNS.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace);
    } catch (Exception e) {
        String err = "Error creating a namespace holder document: " + e.getLocalizedMessage();
        throw new TransformerException(err);
    }
    return rootNS;
}

From source file:Main.java

/**
 * Creates the dom.//  w  w  w  .  ja  v a2 s.co m
 *
 * @param documentElementName
 *            the document element name
 * @return the document
 */
public static Document createDom(String documentElementName) {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        DOMImplementation domImpl = documentBuilder.getDOMImplementation();
        Document document = domImpl.createDocument(NS_PIPELINE_DATA, documentElementName, null);

        return document;

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:Main.java

/**
 * Create document with namespace, qualified name and doc type.
 * /*w  w  w.  ja v a 2  s  . c  o  m*/
 * @param namespaceURI
 *          the namespace URI
 * @param qualifiedName
 *          the qualified name
 * @param doctype
 *          the document type
 * @return the document
 * @throws Exception
 *           on error
 */
public static Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
        throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document document;
    try {
        builder = factory.newDocumentBuilder();
        document = builder.getDOMImplementation().createDocument(namespaceURI, qualifiedName, doctype);
    } catch (Exception e) {
        throw e;
    }
    return document;
}

From source file:Main.java

/**
 * Creates an XML {@link Document} with the provided root element tag.
 * We're using DOM for now - memory-intensive, but OK for these uses
 * @param ns The namespace URI of the document element to create, or null for none.
 * @param rootElement The name of the XML root element tag.
 * @return An XML {@link Document}./*  ww w . j  av a 2 s  .  c om*/
 */
public static Document createXmlDoc(String ns, String rootElement) {
    // Create XML DOM document (Memory consuming).
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
    }
    DOMImplementation impl = builder.getDOMImplementation();
    // Document.
    return impl.createDocument(ns, rootElement, null);
}

From source file:fr.aliasource.webmail.server.proxy.client.http.DOMUtils.java

public static Document createDoc(String namespace, String rootElement)
        throws ParserConfigurationException, FactoryConfigurationError {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  w  ww.j a v  a2  s  .  c  o m*/
    DocumentBuilder builder = dbf.newDocumentBuilder();
    DOMImplementation di = builder.getDOMImplementation();
    return di.createDocument(namespace, rootElement, null);
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static void saveDefaultChart(Chart chart) {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$

    try {/*from w w  w.j  a va 2  s  .c om*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

private static List<Document> runTagger(DocumentBuilder docBuilder, ChemistryPOSTagger tagger,
        List<String> textContent) throws ParserConfigurationException, XPathExpressionException {
    List<Document> tagDocs = new ArrayList<>(textContent.size());
    for (String text : textContent) {
        POSContainer container = tagger.runTaggers(text);
        ChemistrySentenceParser parser = new ChemistrySentenceParser(container);
        parser.parseTags();//from   www . j av a 2 s.c  om
        nu.xom.Document xomDoc = parser.makeXMLDocument();
        DOMImplementation domImpl = docBuilder.getDOMImplementation();
        Document doc = DOMConverter.convert(xomDoc, domImpl);
        tagDocs.add(doc);
    }
    return tagDocs;
}

From source file:com.amalto.webapp.core.util.Util.java

/**
 * Returns a namespaced root element of a document Useful to create a namespace holder element
 * /*from  www.  ja v a 2  s.c  o  m*/
 * @return the root Element
 */
public static Element getRootElement(String elementName, String namespace, String prefix) throws Exception {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Document namespaceHolder = impl.createDocument(namespace,
                (prefix == null ? "" : prefix + ":") + elementName, null); //$NON-NLS-1$ //$NON-NLS-2$
        Element rootNS = namespaceHolder.getDocumentElement();
        rootNS.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace); //$NON-NLS-1$ //$NON-NLS-2$
        return rootNS;
    } catch (Exception e) {
        String err = "Error creating a namespace holder document: " + e.getLocalizedMessage(); //$NON-NLS-1$
        throw new Exception(err);
    }
}

From source file:XsltDomServlet.java

public void init() throws ServletException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {/*w w  w . j a  v  a  2  s .  c  o m*/
        DocumentBuilder db = dbf.newDocumentBuilder();
        dom = db.getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        throw new ServletException(pce);
    }

    // prepare the XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    StreamSource ss = new StreamSource("/var/www/stylesheets/paramTable.xslt");
    try {
        transformer = tf.newTransformer(ss);
    } catch (TransformerConfigurationException tce) {
        throw new ServletException(tce);
    }
}

From source file:Main.java

/**
 * Try to normalize a document by removing nonsignificant whitespace.
 *
 * @see "#62006"//from  ww w  .ja  v a 2s.c  o  m
 */
private static Document normalize(Document orig) throws IOException {
    DocumentBuilder builder = null;
    DocumentBuilderFactory factory = getFactory(false, false);
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N
    }

    DocumentType doctype = null;
    NodeList nl = orig.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i) instanceof DocumentType) {
            // We cannot import DocumentType's, so we need to manually copy it.
            doctype = (DocumentType) nl.item(i);
        }
    }
    Document doc;
    if (doctype != null) {
        doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(),
                orig.getDocumentElement().getTagName(),
                builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(),
                        orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId()));
        // XXX what about entity decls inside the DOCTYPE?
        doc.removeChild(doc.getDocumentElement());
    } else {
        doc = builder.newDocument();
    }
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (!(node instanceof DocumentType)) {
            try {
                doc.appendChild(doc.importNode(node, true));
            } catch (DOMException x) {
                // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions
                throw new IOException("Could not import or append " + node + " of " + node.getClass(), x);
            }
        }
    }
    doc.normalize();
    nl = doc.getElementsByTagName("*"); // NOI18N
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        removeXmlBase(e);
        NodeList nl2 = e.getChildNodes();
        for (int j = 0; j < nl2.getLength(); j++) {
            Node n = nl2.item(j);
            if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) {
                e.removeChild(n);
                j--; // since list is dynamic
            }
        }
    }
    return doc;
}