Example usage for org.w3c.dom Document insertBefore

List of usage examples for org.w3c.dom Document insertBefore

Introduction

In this page you can find the example usage for org.w3c.dom Document insertBefore.

Prototype

public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Source Link

Document

Inserts the node newChild before the existing child node refChild.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element element = doc.createElement("root");
    doc.appendChild(element);//from  w  w w  . j av a  2s . c  o  m
    Comment comment = doc.createComment("This is a comment");
    doc.insertBefore(comment, element);
    Element itemElement = doc.createElement("item");
    element.appendChild(itemElement);
    itemElement.setAttribute("myattr", "attr>value");
    itemElement.insertBefore(doc.createTextNode("te<xt"), itemElement.getLastChild());
    prettyPrint(doc);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);// ww  w . j  a  v a2  s  . c om
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    element = doc.createElement("root");
    doc.appendChild(element);

    Comment comment = doc.createComment("a comment");
    doc.insertBefore(comment, element);

}

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document xmldoc = impl.createDocument(null, "TODOs", null);

    Element root = xmldoc.getDocumentElement();
    Element e0 = xmldoc.createElement("TOPIC");
    Element e1 = xmldoc.createElement("TITLE");
    Node n1 = xmldoc.createTextNode("Java");
    e1.appendChild(n1);//w  ww.jav  a  2  s .c om

    Element e2 = xmldoc.createElement("URL");
    Node n2 = xmldoc.createTextNode("http://www.server.com");
    e2.appendChild(n2);
    e0.appendChild(e1);
    e0.appendChild(e2);
    root.appendChild(e0);

    Node pi = xmldoc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"TODOs.xsl\"");
    xmldoc.insertBefore(pi, root);

    StreamResult out = new StreamResult("howto.xml");
    DOMSource domSource = new DOMSource(xmldoc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(domSource, out);
}

From source file:Main.java

/**
 * Adds stylesheet informations to an xml document. See
 * <a href='http://stackoverflow.com/questions/2651647/add-xml-stylesheet-and-get-standalone-yes'>Stack Overflow</a>.
 *
 * @param aDocument/*w w  w . j  a  v  a2 s.  c  om*/
 * @param aFilename
 */
public static void addStylesheet(Document aDocument, String aFilename) {

    aDocument.setXmlStandalone(true);

    Element root = aDocument.getDocumentElement();

    String data = DATA_STYLESHEET.replace(LOCATION_PLACEHOLDER, aFilename);
    ProcessingInstruction processingInstruction = aDocument.createProcessingInstruction(TARGET_STYLESHEET,
            data);

    aDocument.insertBefore(processingInstruction, root);
}

From source file:Main.java

/**
 * Converts the document from namespace-qualified form into unqualified form by removing all 
 * namespace information.//from w w  w. ja v a2s  .co m
 * 
 * @param document the document to convert
 */

public static void convertFromNamespaceForm(final Document document) {
    final Element oldRootElement = document.getDocumentElement();

    if (oldRootElement != null) {
        final Node nodeAfterRootElement = oldRootElement.getNextSibling();
        final Node newRootElement = convertFromNamespaceForm(oldRootElement);
        document.removeChild(oldRootElement);
        document.insertBefore(newRootElement, nodeAfterRootElement);
    }
}

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

public static void linkToXsl(Document doc, final String xslPath) {
    ProcessingInstruction xsltLink = doc.createProcessingInstruction("xml-stylesheet",
            "type=\"text/xsl\" href=\"" + xslPath + '"');
    Element documentElement = doc.getDocumentElement();
    doc.insertBefore(xsltLink, documentElement);
}

From source file:io.wcm.devops.conga.generator.plugins.fileheader.XmlFileHeader.java

@Override
public Void apply(FileContext file, FileHeaderContext context) {
    try {/*from   w w  w  .j a  va 2  s  .co  m*/
        Document doc = documentBuilder.parse(file.getFile());

        // build XML comment and add it at first position
        Comment comment = doc.createComment("\n" + StringUtils.join(context.getCommentLines(), "\n") + "\n");
        doc.insertBefore(comment, doc.getChildNodes().item(0));

        // write file
        file.getFile().delete();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file.getFile());
        transformer.transform(source, result);
    } catch (SAXException | IOException | TransformerException ex) {
        throw new GeneratorException("Unable to add file header to " + FileUtil.getCanonicalPath(file), ex);
    }
    return null;
}

From source file:com.photon.phresco.plugins.xcode.Instrumentation.java

private void preparePlistResult() throws MojoExecutionException {

    try {//  w ww  .j  a va  2 s .  co  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document xmldoc = dbf.newDocumentBuilder()
                .parse(new File(project.getBasedir().getAbsolutePath() + File.separator + plistResult));
        Element root = xmldoc.getDocumentElement();

        Node pi = xmldoc.createProcessingInstruction("DOCTYPE plist SYSTEM \\",
                "file://localhost/System/Library/DTDs/PropertyList.dtd>");
        xmldoc.insertBefore(pi, root);

        StreamResult out = new StreamResult(
                project.getBasedir().getAbsolutePath() + File.separator + plistResult);

        DOMSource domSource = new DOMSource(xmldoc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Converts the flat .odt filt to a .pef file according to the braille settings.
 *
 * This function/*w  w w. j  a  va2s  .c o m*/
 * <ul>
 * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li>
 * <li>uses {@link LiblouisXML} to translate these files into braille, and</li>
 * <li>recombines these braille files into one single .pef file.</li>
 * </ul>
 *
 * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated
 * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places.
 * The checker checks the DAISY-like files and the volume lengths.
 *
 */

public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException,
        InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception {

    logger.entering("PEF", "makePEF");

    Configuration settings = odt.getConfiguration();

    Element[] volumeElements;
    Element sectionElement;
    File bodyFile = null;
    File brailleFile = null;
    File preliminaryFile = null;

    List<Volume> volumes = manager.getVolumes();

    String volumeInfo = capitalizeFirstLetter(
            ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " "
            + ResourceBundle.getBundle(L10N, settings.mainLocale)
                    .getString((volumes.size() > 1) ? "volumes" : "volume")
            + "\n@title\n@pages";

    volumeElements = new Element[volumes.size()];

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation impl = docBuilder.getDOMImplementation();

    Document document = impl.createDocument(pefNS, "pef", null);
    Element root = document.getDocumentElement();
    root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS);
    root.setAttributeNS(null, "version", "2008-1");

    Element headElement = document.createElementNS(pefNS, "head");
    Element metaElement = document.createElementNS(pefNS, "meta");
    metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date()))));
    metaElement.appendChild(dcElement);
    dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    dcElement.appendChild(document.createTextNode("application/x-pef+xml"));
    metaElement.appendChild(dcElement);
    headElement.appendChild(metaElement);

    root.appendChild(headElement);

    int columns = pefSettings.getColumns();
    int rows = pefSettings.getRows();
    boolean duplex = pefSettings.getDuplex();
    int rowgap = pefSettings.getEightDots() ? 1 : 0;
    int beginPage = settings.getBeginningBraillePageNumber();

    if (statusIndicator != null) {
        statusIndicator.start();
        statusIndicator.setSteps(volumes.size());
        statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale())
                .getString("statusIndicatorStep"));
    }

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {

        volumeElements[volumeCount] = document.createElementNS(pefNS, "volume");
        volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns));
        volumeElements[volumeCount].setAttributeNS(null, "rows",
                String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d)));
        volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap));
        volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false");

        Volume volume = volumes.get(volumeCount);

        // Body section

        logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle());

        if (!(volume instanceof PreliminaryVolume)) {

            bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR);
            bodyFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getBodyMatter(bodyFile, volume);
            liblouisXML.configure(bodyFile, brailleFile, false, beginPage);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1);
            volumeElements[volumeCount].appendChild(sectionElement);

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(bodyFile);
            }

            // Braille page range
            volume.setBraillePagesStart(beginPage);
            volume.setNumberOfBraillePages(pageCount);
            beginPage += pageCount;

            // Print page range
            if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) {
                extractPrintPageRange(bodyFile, volume, settings);
            }
        }

        // Special symbols list
        if (volume.getSpecialSymbolListEnabled()) {
            extractSpecialSymbols(bodyFile, volume, volumeCount, settings);
        }

        // Preliminary section

        if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled()
                || volume.getSpecialSymbolListEnabled()) {

            preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml",
                    TMP_DIR);
            preliminaryFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, true,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Page range
            int pageCount = countPages(brailleFile, volume);
            volume.setNumberOfPreliminaryPages(pageCount);

            // Translate again with updated volume info and without volume separator marks
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();
            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, false,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount);
            volumeElements[volumeCount].insertBefore(sectionElement,
                    volumeElements[volumeCount].getFirstChild());

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(preliminaryFile);
            }
        }

        if (statusIndicator != null) {
            statusIndicator.increment();
        }
    }

    if (checker != null) {
        checker.checkVolumes(volumes);
    }

    Element bodyElement = document.createElementNS(pefNS, "body");

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {
        bodyElement.appendChild(volumeElements[volumeCount]);
    }

    root.appendChild(bodyElement);

    document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet",
            "type='text/css' href='pef.css'"), document.getFirstChild());

    OdtUtils.saveDOM(document, pefFile);

    logger.exiting("PEF", "makePEF");

    if (!validatePEF(pefFile)) {
        return false;
    }

    return true;
}