Example usage for javax.xml.parsers DocumentBuilder newDocument

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

Introduction

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

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:uk.co.markfrimston.tasktree.TaskTree.java

protected Document saveToDocument() throws Exception {
    DocumentBuilder builder = builderFact.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element taskList = doc.createElement("tasklist");
    doc.appendChild(taskList);/*  w ww.j  av a  2  s  .c o m*/
    taskList.appendChild(doc.createTextNode("\n\t"));
    Element tasks = doc.createElement("tasks");
    taskList.appendChild(tasks);
    taskList.appendChild(doc.createTextNode("\n"));
    addChildElementsFromTasks(doc, tasks, root, 1);

    return doc;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

private Node makeEntityResolutionConfigurationNode(String limit) throws Exception {
    try {//from w  w  w .  ja  va2  s  . co m
        if (Integer.parseInt(limit) == Integer.MAX_VALUE) {
            return null;
        }
    } catch (NumberFormatException nfe) {
        return null;
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.newDocument();
    Element ret = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE,
            "EntityResolutionConfiguration");
    d.appendChild(ret);
    Element e = d.createElementNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "RecordLimit");
    ret.appendChild(e);
    e.setTextContent(limit);
    return ret;
}

From source file:Interface.MainJFrame.java

private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed
    // TODO add your handling code here:
    try {/*from  w w w. ja v a  2s  .com*/

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Employees");
        doc.appendChild(rootElement);

        // staff elements
        String empTitle = txtEmployeeType.getText().trim();
        empTitle = empTitle.replace(" ", "");
        Element staff = doc.createElement(empTitle);
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("ID");
        attr.setValue(txtEmployeeID.getText().trim());
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // FullName elements
        Element FulllName = doc.createElement("FulllName");
        FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim()));
        staff.appendChild(FulllName);

        // Phone elements
        Element Phone = doc.createElement("PhoneNumber");
        Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim()));
        staff.appendChild(Phone);

        // Address elements
        Element Address = doc.createElement("Address");
        Address.appendChild(doc.createTextNode(txtAddress.getText().trim()));
        staff.appendChild(Address);

        // Title elements
        Element Title = doc.createElement("Tile");
        Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim()));
        staff.appendChild(Title);

        // PayCategory elements
        Element PayCategory = doc.createElement("PayCategory");
        PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim()));
        staff.appendChild(PayCategory);

        // Salary elements
        Element Salary = doc.createElement("Salary");
        Salary.appendChild(doc.createTextNode(txtSalary.getText().trim()));
        staff.appendChild(Salary);

        // Hours elements

        String hours = txtHours.getText().trim();
        if (txtHours.getText().equalsIgnoreCase("") || hours == null) {
            hours = "null";
        }
        Element Hours = doc.createElement("Hours");
        Hours.appendChild(doc.createTextNode(hours));
        staff.appendChild(Hours);

        // Bonus elements
        Element Bonus = doc.createElement("Bonus");
        Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim()));
        staff.appendChild(Bonus);

        // Total elements
        Element Total = doc.createElement("Total");
        Total.appendChild(doc.createTextNode(txtTotal.getText().trim()));
        staff.appendChild(Total);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("XMLOutput"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }

}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * Xpath performance degrades on large documents so this workaround was needed to improve performance. See link inline in the code.
 * /*from  w w  w .  java2s.  com*/
 * @param entityElement
 * @return
 * @throws ParserConfigurationException
 */
private Element createOrphanElement(Element entityElement) throws ParserConfigurationException {

    // this is necessary to avoid a performance bottleneck in the Xalan xpath engine
    // see http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dummyDocument = db.newDocument();
    dummyDocument.appendChild(dummyDocument.importNode(entityElement, true));
    entityElement = dummyDocument.getDocumentElement();

    return entityElement;

}

From source file:au.edu.rmit.GalagoSearchClient.java

protected Document runSnippet(String id, List<String> terms)
        throws ParserConfigurationException, UnsupportedEncodingException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    XPath xpath = XPathFactory.newInstance().newXPath();

    String baseURI = "http://" + this.host + ":" + Integer.toString(this.port) + "/snippet";
    String uri = baseURI + "?identifier=" + id;
    for (String term : terms)
        uri += "&term=" + URLEncoder.encode(term, "UTF-8");

    Document result;/*from   w  w  w .  ja v a  2 s  . co m*/

    try {
        result = builder.parse(uri);
    } catch (Exception e) {
        e.printStackTrace();
        result = builder.newDocument();
    }

    return result;
}

From source file:com.msopentech.odatajclient.engine.data.impl.AbstractODataBinder.java

protected Element newEntryContent() {
    Element properties = null;//w  w w  . j  a v  a  2s .co m
    try {
        final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.newDocument();
        properties = doc.createElement(ODataConstants.ELEM_PROPERTIES);
        properties.setAttribute(ODataConstants.XMLNS_METADATA,
                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
        properties.setAttribute(ODataConstants.XMLNS_DATASERVICES,
                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
        properties.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
        properties.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    } catch (ParserConfigurationException e) {
        LOG.error("Failure building entry content", e);
    }

    return properties;
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

public void saveConfig() throws Exception {
    try {/*  w w  w. j  ava2s .c om*/
        DocumentBuilder builder = builderFact.newDocumentBuilder();
        Document doc = builder.newDocument();
        //doc.appendChild(doc.createTextNode("\n"));
        Element elConfig = doc.createElement("config");
        doc.appendChild(elConfig);
        elConfig.appendChild(doc.createTextNode("\n"));

        makeConfigEl(doc, elConfig, "load-url", "URL used to load task tree from remote server", loadUrl);

        makeConfigEl(doc, elConfig, "save-url", "URL used to save task tree to remote server", saveUrl);

        makeConfigEl(doc, elConfig, "merge-command",
                "Command executed to merge task tree versions. " + "Use {0} for local file, {1} for remote",
                mergeCommand);

        if (lastSyncTime == null) {
            lastSyncTime = 0L;
        }
        makeConfigEl(doc, elConfig, "last-sync", "Timestamp of last sync. Do not edit!", lastSyncTime);

        if (unsynchedChanges == null) {
            unsynchedChanges = true;
        }
        makeConfigEl(doc, elConfig, "unsynched-changes", "Changes made since last sync. Do not edit!",
                unsynchedChanges);

        elConfig.appendChild(doc.createTextNode("\n"));

        makeFilePath();
        File file = new File(filePath + CONFIG_FILENAME);
        FileOutputStream fileStream = new FileOutputStream(file);
        writeDocToStream(doc, fileStream);
        fileStream.close();
    } catch (Exception e) {
        throw new Exception("Failed to save config file: " + e.getClass().getName() + " - " + e.getMessage());
    }
}

From source file:com.photon.phresco.service.tools.TechnologyDataGenerator.java

/**
 * Create pom.xml file for each module//from  ww w .  j a va2  s .  co  m
 * @param module
 * @param ext
 * @param groupId2
 * @return
 * @throws PhrescoException
 */
private File createPomFile(String name, String groupId, String artifactId, String version, String ext)
        throws PhrescoException {
    System.out.println("Creating Pom File For " + name);
    File file = new File(outputRootDir, "pom.xml");
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

        org.w3c.dom.Document newDoc = domBuilder.newDocument();
        Element rootElement = newDoc.createElement("project");
        newDoc.appendChild(rootElement);

        Element modelVersion = newDoc.createElement("modelVersion");
        modelVersion.setTextContent("4.0.0");
        rootElement.appendChild(modelVersion);

        Element groupIdEle = newDoc.createElement("groupId");
        groupIdEle.setTextContent(groupId);
        rootElement.appendChild(groupIdEle);

        Element artifactIdEle = newDoc.createElement("artifactId");
        artifactIdEle.setTextContent(artifactId);
        rootElement.appendChild(artifactIdEle);

        Element versionEle = newDoc.createElement("version");
        versionEle.setTextContent(version);
        rootElement.appendChild(versionEle);

        Element packaging = newDoc.createElement("packaging");
        packaging.setTextContent(ext);
        rootElement.appendChild(packaging);

        Element description = newDoc.createElement("description");
        description.setTextContent("created by phresco");
        rootElement.appendChild(description);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(newDoc);
        trans.transform(source, result);
        String xmlString = sw.toString();
        FileWriter writer = new FileWriter(file);
        writer.write(xmlString);
        writer.close();

    } catch (Exception e) {
        throw new PhrescoException();
    }
    return file;
}

From source file:com.msopentech.odatajclient.engine.data.AbstractODataBinder.java

protected Element newEntryContent() {
    Element properties = null;//from   ww w  .j a  v  a 2  s  .co m
    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.newDocument();
        properties = doc.createElement(ODataConstants.ELEM_PROPERTIES);
        properties.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
        properties.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
        properties.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
        properties.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    } catch (ParserConfigurationException e) {
        LOG.error("Failure building entry content", e);
    }

    return properties;
}

From source file:gov.usda.DataCatalogClient.Catalog.java

public void toLegacyXML(String xmlFileName, DataListingCode dataListingType) {
    Element catalogElement = null;
    try {/*ww  w.jav  a2 s  . c o  m*/
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        catalogElement = doc.createElement("catalog");
        for (Dataset ds : dataSetList) {
            if (dataListingType.equals(DataListingCode.PUBLIC_DATA_LISTING)) {
                String publicAccessLevel = ds.getAccessLevel();
                if (publicAccessLevel.equals(Dataset.AccessLevel.PUBLIC.toString())
                        || publicAccessLevel.equals(Dataset.AccessLevel.RESTRICTED.toString())) {
                    catalogElement.appendChild(ds.toLegacyXML(doc));
                }
            }
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(catalogElement);
        StreamResult result = new StreamResult(new File(xmlFileName));
        transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException e) {
        log.log(Level.SEVERE, "Error in field to Legacy dataset " + title + " " + e.toString());
    }
}