Example usage for org.w3c.dom.ls DOMImplementationLS createLSSerializer

List of usage examples for org.w3c.dom.ls DOMImplementationLS createLSSerializer

Introduction

In this page you can find the example usage for org.w3c.dom.ls DOMImplementationLS createLSSerializer.

Prototype

public LSSerializer createLSSerializer();

Source Link

Document

Create a new LSSerializer object.

Usage

From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java

protected void writeXmlFile(final Document doc, final File workDirectory, final String fileName)
        throws MojoFailureException {
    final File destinationFile = new File(workDirectory, fileName);
    try {//from  w  w  w .j  av  a 2 s .c  om
        final FileOutputStream ostream = new FileOutputStream(destinationFile);
        final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        final LSSerializer lsSerializer = domImplementation.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);

        final LSOutput lsOutput = domImplementation.createLSOutput();
        lsOutput.setByteStream(ostream);
        lsSerializer.write(doc, lsOutput);

        ostream.close();
        refreshEclipse(destinationFile);
    } catch (final Exception e) {
        throw new MojoFailureException("Cannot write output file", e);
    }
}

From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java

private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
    DOMHandle handle = new DOMHandle();
    HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
    Document combinedQueryXml = handle.get();
    DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("xml-declaration", false);

    NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
    Node n = nl.item(0);//from w w  w  . j av  a2 s.  co  m
    String options = null;
    StringHandle optionsHandle = null;
    if (n != null) {
        options = lsSerializer.writeToString(n);
        optionsHandle = new StringHandle(options).withFormat(Format.XML);
    }

    //TODO this could be more than one string...
    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
    n = nl.item(0);
    String qtext = null;
    if (n != null) {
        qtext = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
    n = nl.item(0);
    String sparql = null;
    if (n != null) {
        sparql = lsSerializer.writeToString(n);
    }

    nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
    n = nl.item(0);
    String query = null;
    if (n != null) {
        query = lsSerializer.writeToString(nl.item(0));
    }
    StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
    RawStructuredQueryDefinition structuredQueryDefinition = new RawQueryDefinitionImpl.Structured(
            structuredQueryHandle);
    return new CombinedQueryDefinitionImpl(structuredQueryDefinition, optionsHandle, qtext, sparql);
}

From source file:org.coronastreet.gpxconverter.Converter.java

private void dumpNode(Element e) {
    Document document = e.getOwnerDocument();
    DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
    LSSerializer serializer = domImplLS.createLSSerializer();
    String str = serializer.writeToString(e);
    log("XML::: " + str);
}

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {/*  w  w w. ja  v  a  2  s .c o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/*from ww  w  . j  a va  2 s .  co  m*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignature(Object signatureId, Document document, Document originalData,
        SignatureParameters parameters) throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }// w ww.  j  av  a2 s  .  c  o  m

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            String sid = signatureEl.getAttribute("Id");
            if (signatureId.equals(sid)) {
                extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
            }
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private String prettifyXml(Document doc) {
    try {//from   ww w  .  j a v  a 2 s.c  o m
        DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                .getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        return writer.writeToString(doc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * @throws   IllegalStateException/*from   w w  w .  j  a va  2  s .co m*/
 *          If java's DOMImplementationLS class is screwed up or
 *          this code is buggy
 * @param document
 * @return
 */
private String serializeDocument(Document document) {

    try {
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMImplementationSourceImpl");
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        final LSSerializer writer = impl.createLSSerializer();
        final String str = writer.writeToString(document);

        return str;

    } catch (final ClassNotFoundException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    } catch (final InstantiationException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    } catch (final IllegalAccessException e) {
        final IllegalStateException ise = new IllegalStateException();
        ise.initCause(e);
        throw ise;
    }

}

From source file:eumetsat.pn.common.ISO2JSON.java

private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException {
    String expression = null;//w  w  w .j  av  a  2s  .  c o m
    String result = null;
    XPath xPath = XPathFactory.newInstance().newXPath();
    JSONObject jsonObject = new JSONObject();

    String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']";
    String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument);
    log.trace("{} >>> {}", xpathFileID, fileID);
    if (fileID != null) {
        jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID);
    }

    expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']";
    JSONArray list = new JSONArray();
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }
    if (list.size() > 0) {
        JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list);
        hierarchies.writeJSONString(writer);
        jsonObject.put("hierarchyNames", hierarchies);
        log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames"));
    }

    // Get Contact info
    String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']";
    String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']";
    String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']";
    String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']";
    String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']";
    String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']";

    StringBuilder addressString = new StringBuilder();
    StringBuilder emailString = new StringBuilder();

    appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint);

    result = xPath.compile(postalCode).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(city).evaluate(xmlDocument);
    if (result != null) {
        addressString.append(" ").append(result.trim());
    }

    result = xPath.compile(administrativeArea).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(country).evaluate(xmlDocument);
    if (result != null) {
        addressString.append("\n").append(result.trim());
    }

    result = xPath.compile(email).evaluate(xmlDocument);
    if (result != null) {
        emailString.append(result.trim());
    }

    HashMap<String, String> map = new HashMap<>();
    map.put("address", addressString.toString());
    map.put("email", emailString.toString());
    jsonObject.put("contact", map);
    log.trace("contact: {}", Arrays.toString(map.entrySet().toArray()));

    // add identification info
    String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']";
    String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']";
    String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue";
    String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']";

    HashMap<String, Object> idMap = new HashMap<>();

    result = xPath.compile(titleStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("title", result.trim());
    }

    result = xPath.compile(abstractStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("abstract", result.trim());
    }

    result = xPath.compile(statusStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("status", result.trim());
    }

    list = new JSONArray();
    nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        list.add(nodeList.item(i).getFirstChild().getNodeValue());
    }

    if (list.size() > 0) {
        idMap.put("keywords", list);
    }

    jsonObject.put("identificationInfo", idMap);
    log.trace("idMap: {}", idMap);

    // get thumbnail product
    String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']";
    result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument);
    if (result != null) {
        idMap.put("thumbnail", result.trim());
        log.trace("thumbnail: {}", result);
    }

    // add Geo spatial information
    String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']";
    String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']";
    String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']";
    String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']";

    // create a GeoJSON envelope object
    HashMap<String, Object> latlonMap = new HashMap<>();
    latlonMap.put("type", "envelope");

    JSONArray envelope = new JSONArray();
    JSONArray leftTopPt = new JSONArray();
    JSONArray rightDownPt = new JSONArray();

    result = xPath.compile(westBLonStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(northBLatStr).evaluate(xmlDocument);
    if (result != null) {
        leftTopPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(eastBLonStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    result = xPath.compile(southBLatStr).evaluate(xmlDocument);
    if (result != null) {
        rightDownPt.add(Double.parseDouble(result.trim()));
    }

    envelope.add(leftTopPt);
    envelope.add(rightDownPt);

    latlonMap.put("coordinates", envelope);
    jsonObject.put("location", latlonMap);

    DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    String xmlString = lsSerializer.writeToString(xmlDocument);

    jsonObject.put("xmldoc", xmlString);

    return jsonObject;
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Generate an xml file with the specified collections.
 * //from  w  w  w .j a va2s .co  m
 * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection)
 */
public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections,
        boolean includeChildren) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    Set<FileInfo> allPictures = new HashSet<FileInfo>();
    String path = FilenameUtils.getPath(f.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!f.exists()) {
        if (!f.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "institutionalCollections", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(f);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (InstitutionalCollection c : collections) {
        Element collection = doc.createElement("collection");

        this.addIdElement(collection, c.getId().toString(), doc);
        this.addNameElement(collection, c.getName(), doc);
        this.addDescription(collection, c.getDescription(), doc);
        this.addCopyright(collection, c.getCopyright(), doc);

        if (c.getPrimaryPicture() != null) {
            this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc);
            allPictures.add(c.getPrimaryPicture().getFileInfo());
        }
        Set<IrFile> pictures = c.getPictures();

        if (pictures.size() > 0) {
            Element pics = doc.createElement("pictures");
            for (IrFile irFile : pictures) {
                Element picture = doc.createElement("picture");
                this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc);
                pics.appendChild(picture);
                allPictures.add(irFile.getFileInfo());
            }
            collection.appendChild(pics);
        }

        if (c.getLinks().size() > 0) {
            Element links = doc.createElement("links");
            for (InstitutionalCollectionLink l : c.getLinks()) {
                this.addLink(links, l, doc);
            }
            collection.appendChild(links);
        }

        if (includeChildren) {
            for (InstitutionalCollection child : c.getChildren()) {
                addChild(child, collection, doc, allPictures);
            }
        }
        root.appendChild(collection);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return allPictures;
}