Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Connects to fbox service xml to get a list of all services which are offered
 * by TR064. Saves it into local list./*  w w  w.  j a v a2  s . c om*/
 */
private void readAllServices() {
    Document xml = getFboxXmlResponse(_url + "/" + TR064DOWNLOADFILE);
    if (xml == null) {
        logger.error("Could not read xml response services");
        return;
    }
    NodeList nlServices = xml.getElementsByTagName("service"); // get all service nodes
    Node currentNode = null;
    XPath xPath = XPathFactory.newInstance().newXPath();
    for (int i = 0; i < nlServices.getLength(); i++) { // iterate over all services fbox offered us
        currentNode = nlServices.item(i);
        Tr064Service trS = new Tr064Service();
        try {
            trS.setControlUrl((String) xPath.evaluate("controlURL", currentNode, XPathConstants.STRING));
            trS.setEventSubUrl((String) xPath.evaluate("eventSubURL", currentNode, XPathConstants.STRING));
            trS.setScpdurl((String) xPath.evaluate("SCPDURL", currentNode, XPathConstants.STRING));
            trS.setServiceId((String) xPath.evaluate("serviceId", currentNode, XPathConstants.STRING));
            trS.setServiceType((String) xPath.evaluate("serviceType", currentNode, XPathConstants.STRING));
        } catch (XPathExpressionException e) {
            logger.debug("Could not parse service {}", currentNode.getTextContent());
            e.printStackTrace();
        }
        _allServices.put(trS.getServiceId(), trS);
    }
}

From source file:org.openhab.binding.ihc.ws.IhcResourceInteractionService.java

private String getValue(Node n, String expr) throws XPathExpressionException {

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String prefix) {

            if (prefix == null) {
                throw new NullPointerException("Null prefix");
            } else if ("SOAP-ENV".equals(prefix)) {
                return "http://schemas.xmlsoap.org/soap/envelope/";
            } else if ("ns1".equals(prefix)) {
                return "utcs";
            }/*from  w  w w.  j  a v  a  2s .  c  o  m*/
            // else if ("ns2".equals(prefix)) return "utcs.values";
            return "utcs.values";
            // return null;
        }

        public String getPrefix(String uri) {
            return null;
        }

        @SuppressWarnings("rawtypes")
        public Iterator getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression pathExpr = xpath.compile(expr);
    return (String) pathExpr.evaluate(n, XPathConstants.STRING);
}

From source file:org.opennaas.extensions.router.junos.actionssets.actions.topologydiscovery.GetInterfaceNeighbourAction.java

@Override
public void parseResponse(Object responseMessage, Object model) throws ActionException {

    log.info("Parsing netconf response");

    if (!(responseMessage instanceof Reply))
        throw new CommandException("Error parsing response: the response is not a Reply message");

    Reply rpcReply = (Reply) responseMessage;
    String message = rpcReply.getContain();

    if (message != null) {
        try {/*  w  ww .j  a v  a2s  . c o  m*/

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document xmlDocument = builder.parse(new ByteArrayInputStream(message.getBytes()));

            XPath xPath = XPathFactory.newInstance().newXPath();

            rpcResponse = (String) xPath.compile(REMOTE_PORT_ID_TAG).evaluate(xmlDocument,
                    XPathConstants.STRING);

        } catch (Exception e) {
            log.error("Error parsing netconf message: ", e);
            throw new ActionException(e);
        }

    }

}

From source file:org.opennaas.extensions.router.junos.actionssets.actions.topologydiscovery.GetLocalInformationAction.java

@Override
public void parseResponse(Object responseMessage, Object model) throws ActionException {

    log.info("Parsing netconf response");

    if (!(responseMessage instanceof Reply))
        throw new CommandException("Error parsing response: the response is not a Reply message");

    Reply rpcReply = (Reply) responseMessage;
    String message = rpcReply.getContain();

    if (message != null) {
        try {// ww w  . java2 s .co m
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            XPath xPath = XPathFactory.newInstance().newXPath();
            Document xmlDocument = builder.parse(new ByteArrayInputStream(message.getBytes()));

            String deviceId = (String) xPath.compile(LOCAL_ID_PATH).evaluate(xmlDocument,
                    XPathConstants.STRING);
            NodeList interfaces = (NodeList) xPath.compile(LOCAL_IFACE_INFO_PATH).evaluate(xmlDocument,
                    XPathConstants.NODESET);

            Map<String, String> ifacesMap = new HashMap<String, String>();

            for (int i = 0; i < interfaces.getLength(); i++) {

                Element element = (Element) interfaces.item(i);
                String ifaceName = element.getElementsByTagName(LOCAL_IFACE_NAME_TAG).item(0).getTextContent();
                String portId = element.getElementsByTagName(LOCAL_IFACE_ID_TAG).item(0).getTextContent();

                ifacesMap.put(portId, ifaceName);

            }

            rpcResponse = new LocalInformation();
            rpcResponse.setDeviceId(deviceId);
            rpcResponse.setInterfacesMap(ifacesMap);

        } catch (Exception e) {
            log.error("Error parsing netconf message: ", e);
            throw new ActionException(e);
        }

    }

}

From source file:org.opennms.protocols.xml.collector.AbstractXmlCollectionHandler.java

/**
 * Fill collection set./*from w  ww  . ja  v a 2  s  .  co m*/
 *
 * @param agent the agent
 * @param collectionSet the collection set
 * @param source the source
 * @param doc the doc
 * @throws XPathExpressionException the x path expression exception
 * @throws ParseException the parse exception
 */
protected void fillCollectionSet(CollectionAgent agent, XmlCollectionSet collectionSet, XmlSource source,
        Document doc) throws XPathExpressionException, ParseException {
    XmlCollectionResource nodeResource = new XmlSingleInstanceCollectionResource(agent);
    NamespaceContext nc = new DocumentNamespaceResolver(doc);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(nc);
    for (XmlGroup group : source.getXmlGroups()) {
        LOG.debug("fillCollectionSet: getting resources for XML group {} using XPATH {}", group.getName(),
                group.getResourceXpath());
        Date timestamp = getTimeStamp(doc, xpath, group);
        NodeList resourceList = (NodeList) xpath.evaluate(group.getResourceXpath(), doc,
                XPathConstants.NODESET);
        for (int j = 0; j < resourceList.getLength(); j++) {
            Node resource = resourceList.item(j);
            String resourceName = getResourceName(xpath, group, resource);
            XmlCollectionResource collectionResource;
            if (group.getResourceType().equalsIgnoreCase(CollectionResource.RESOURCE_TYPE_NODE)) {
                collectionResource = nodeResource;
            } else {
                collectionResource = getCollectionResource(agent, resourceName, group.getResourceType(),
                        timestamp);
            }
            LOG.debug("fillCollectionSet: processing resource {}", collectionResource);
            AttributeGroupType attribGroupType = new AttributeGroupType(group.getName(), group.getIfType());
            for (XmlObject object : group.getXmlObjects()) {
                String value = (String) xpath.evaluate(object.getXpath(), resource, XPathConstants.STRING);
                XmlCollectionAttributeType attribType = new XmlCollectionAttributeType(object, attribGroupType);
                collectionResource.setAttributeValue(attribType, value);
            }
            processXmlResource(collectionResource, attribGroupType);
            LOG.debug("fillCollectionSet: adding collection resource {}", collectionResource);
            collectionSet.getCollectionResources().add(collectionResource);
        }
    }
    XmlAttributeCounter counter = new XmlAttributeCounter();
    collectionSet.visit(counter);
    LOG.debug("fillCollectionSet: finishing collection set with {} resources and {} attributes on {}",
            collectionSet.getCollectionResources().size(), counter.getCount(), agent);
}

From source file:org.orcid.core.cli.LoadFundRefData.java

/**
 * Get an RDF organization from the given RDF file
 * *///from  w w w .ja  va2 s  . c o m
private RDFOrganization getOrganization(Document xmlDocument, NamedNodeMap attrs) {
    RDFOrganization organization = new RDFOrganization();
    try {
        Node node = attrs.getNamedItem("rdf:resource");
        String itemDoi = node.getNodeValue();
        LOGGER.info("Processing item {}", itemDoi);
        // Get organization name
        String orgName = (String) xPath.compile(orgNameExpression.replace("%s", itemDoi)).evaluate(xmlDocument,
                XPathConstants.STRING);
        // Get country code
        Node countryNode = (Node) xPath.compile(orgCountryExpression.replace("%s", itemDoi))
                .evaluate(xmlDocument, XPathConstants.NODE);
        NamedNodeMap countryAttrs = countryNode.getAttributes();
        String countryGeonameUrl = countryAttrs.getNamedItem("rdf:resource").getNodeValue();
        String countryCode = fetchFromGeoNames(countryGeonameUrl, "countryCode");

        // Get state name
        Node stateNode = (Node) xPath.compile(orgStateExpression.replace("%s", itemDoi)).evaluate(xmlDocument,
                XPathConstants.NODE);
        String stateName = null;
        String stateCode = null;
        if (stateNode != null) {
            NamedNodeMap stateAttrs = stateNode.getAttributes();
            String stateGeoNameCode = stateAttrs.getNamedItem("rdf:resource").getNodeValue();
            stateName = fetchFromGeoNames(stateGeoNameCode, "name");
            stateCode = fetchFromGeoNames(stateGeoNameCode, STATE_NAME);
        }

        // Get type
        String orgType = (String) xPath.compile(orgTypeExpression.replace("%s", itemDoi)).evaluate(xmlDocument,
                XPathConstants.STRING);
        // Get subType
        String orgSubType = (String) xPath.compile(orgSubTypeExpression.replace("%s", itemDoi))
                .evaluate(xmlDocument, XPathConstants.STRING);

        // Fill the organization object
        organization.doi = itemDoi;
        organization.name = orgName;
        organization.country = countryCode;
        organization.state = stateName;
        organization.stateCode = stateCode;
        // TODO: since we don't have city, we fill this with the state, this
        // should be modified soon
        organization.city = stateCode;
        organization.type = orgType;
        organization.subtype = orgSubType;
    } catch (XPathExpressionException xpe) {
        LOGGER.error("XPathExpressionException {}", xpe.getMessage());
    }

    return organization;
}

From source file:org.pentaho.js.require.RequireJsGenerator.java

public static String getWebjarVersionFromPom(InputStream inputStream) throws IOException,
        ParserConfigurationException, SAXException, XPathExpressionException, ParseException {
    byte[] bytes = IOUtils.toByteArray(inputStream);
    Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new ByteArrayInputStream(bytes));

    XPath xPath = XPathFactory.newInstance().newXPath();

    final Element document = pom.getDocumentElement();

    return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
}

From source file:org.pentaho.js.require.RequireJsGenerator.java

private void requirejsFromPom(Document pom) throws XPathExpressionException, ParseException {

    XPath xPath = XPathFactory.newInstance().newXPath();

    final Element document = pom.getDocumentElement();

    moduleInfo = new ModuleInfo((String) xPath.evaluate("/project/artifactId", document, XPathConstants.STRING),
            (String) xPath.evaluate("/project/version", document, XPathConstants.STRING));

    String pomConfig = (String) xPath.evaluate("/project/properties/requirejs", document,
            XPathConstants.STRING);

    requireConfig = (Map<String, Object>) parser.parse(pomConfig);

    NodeList pomDependencies = (NodeList) xPath.evaluate(
            "/project/dependencies/dependency[contains(groupId, 'org.webjars')]", document,
            XPathConstants.NODESET);
    for (int i = 0, ic = pomDependencies.getLength(); i != ic; ++i) {
        Node dependency = pomDependencies.item(i);

        NodeList dependencyChildNodes = dependency.getChildNodes();

        String dependencyGroupId = null;
        String dependencyArtifactId = null;
        String dependencyVersion = null;

        for (int j = 0, jc = dependencyChildNodes.getLength(); j != jc; ++j) {
            Node item = dependencyChildNodes.item(j);
            String nodeName = item.getNodeName();

            if (nodeName.equals("groupId")) {
                dependencyGroupId = item.getChildNodes().item(0).getNodeValue();
            }/*from  w w w  . jav a  2s  .c o m*/

            if (nodeName.equals("artifactId")) {
                dependencyArtifactId = item.getChildNodes().item(0).getNodeValue();
            }

            if (nodeName.equals("version")) {
                dependencyVersion = item.getChildNodes().item(0).getNodeValue();
            }
        }

        dependencies.put("mvn:" + dependencyGroupId + "/" + dependencyArtifactId, dependencyVersion);
    }
}

From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java

public static String getWebjarVersionFromPom(InputStream inputStream) throws Exception {
    try {/* ww w. ja v  a  2 s .com*/
        byte[] bytes = IOUtils.toByteArray(inputStream);
        Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(bytes));

        XPath xPath = XPathFactory.newInstance().newXPath();

        final Element document = pom.getDocumentElement();

        return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
    } catch (Exception e) {
        throw new Exception("Error reading JS script", e);
    }
}

From source file:org.rdswicthboard.utils.rdf.oai.App.java

public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file");
    options.addOption("o", PROPERTY_OUTPUT_FILE, true,
            "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")");
    options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")");
    options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")");
    options.addOption("I", PROPERTY_INPUT_ENCODING, true,
            "input file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("O", PROPERTY_OUTPUT_ENCODING, true,
            "output file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding");
    options.addOption("h", PROPERTY_HELP, false, "print this message");

    try {//from  ww  w. ja va2 s .  c o m
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(PROPERTY_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]",
                    options);

            System.exit(0);
        }

        // variables to store program properties
        CompositeConfiguration config = new CompositeConfiguration();
        config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE);
        config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC);
        config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT);

        // check if arguments has input file properties 
        if (line.hasOption(PROPERTY_CONFIG_FILE)) {
            // if it does, load the specified configuration file
            Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE));
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            } else
                throw new Exception("Invalid configuration file: " + defaultConfig.toString());
        } else {
            // if it not, try to load default configurationfile
            Path defaultConfig = Paths.get(PROPERTIES_FILE);
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            }
        }

        // check if arguments has input file 
        if (line.hasOption(PROPERTY_INPUT_FILE))
            config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE));

        // check if arguments has output file
        if (line.hasOption(PROPERTY_OUTPUT_FILE))
            config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE));

        // check if arguments has set spec name
        if (line.hasOption(PROPERTY_SET_SPEC))
            config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC));

        // check if arguments has input encoding
        if (line.hasOption(PROPERTY_INPUT_ENCODING))
            config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_OUTPUT_ENCODING))
            config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_FORMAT_OUTPUT))
            config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes");

        // check if arguments has input file without a key
        if (line.getArgs().length > 0) {
            config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]);

            // check if arguments has output file without a key
            if (line.getArgs().length > 1) {
                config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]);

                // check if there is too many arguments
                if (line.getArgs().length > 2)
                    throw new Exception("Too many arguments");
            }
        }

        // The program has default output file, but input file must be presented
        if (!config.containsKey(PROPERTY_INPUT_FILE))
            throw new Exception("Please specify input file");

        // extract input file
        String inputFile = config.getString(PROPERTY_INPUT_FILE);

        // extract output file
        String outputFile = config.getString(PROPERTY_OUTPUT_FILE);

        // extract set spec
        String setSpecName = config.getString(PROPERTY_SET_SPEC);

        // extract encoding
        String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING);
        String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING);

        boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT);

        // test if source is an regular file and it is readable
        Path source = Paths.get(inputFile);
        if (!Files.isRegularFile(source))
            throw new Exception("The input file: " + source.toString() + " is not an regular file");
        if (!Files.isReadable(source))
            throw new Exception("The input file: " + source.toString() + " is not readable");

        Path target = Paths.get(outputFile);
        if (Files.exists(target)) {
            if (!Files.isRegularFile(target))
                throw new Exception("The output file: " + target.toString() + " is not an regular file");
            if (!Files.isWritable(target))
                throw new Exception("The output file: " + target.toString() + " is not writable");
        }

        // create and setup document builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        // create new document builder
        DocumentBuilder builder = factory.newDocumentBuilder();

        // create oai document
        Document oai = builder.newDocument();

        // set document version
        oai.setXmlVersion("1.0");
        oai.setXmlStandalone(true);

        // create root OAI-PMH element
        Element oaiPmh = oai.createElement("OAI-PMH");

        // set document namespaces
        oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
        oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        oaiPmh.setAttribute("xsi:schemaLocation",
                "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");

        // append root node
        oai.appendChild(oaiPmh);

        // create responseDate element
        Element responseDate = oai.createElement("responseDate");

        // create simple date format
        DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);

        // generate date
        String date = dateFormat.format(new Date());

        // set current date and time
        responseDate.setTextContent(date);

        oaiPmh.appendChild(responseDate);

        Element listRecords = oai.createElement("ListRecords");
        oaiPmh.appendChild(listRecords);

        // create xpath factory
        XPathFactory xPathfactory = XPathFactory.newInstance();

        // create namespace context
        NamespaceContext namespaceContext = new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if (prefix.equals("rdf"))
                    return RDF_NAMESPACE;
                else if (prefix.equals("rns"))
                    return RNF_NAMESPACE;
                else
                    return null;
            }

            @Override
            public Iterator<?> getPrefixes(String val) {
                throw new IllegalAccessError("Not implemented!");
            }

            @Override
            public String getPrefix(String uri) {
                throw new IllegalAccessError("Not implemented!");
            }
        };

        // create xpath object
        XPath xpath = xPathfactory.newXPath();
        // set namespace contex
        xpath.setNamespaceContext(namespaceContext);

        // create XPath expressions
        XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about");
        XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']");

        // create RegEx patterns  
        Pattern pattern = Pattern.compile(
                "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>");

        // read file into a string
        String content = new String(Files.readAllBytes(source), inputEncoding);

        Matcher matcher = pattern.matcher(content);
        // process all records
        while (matcher.find()) {
            // convert string to input stream
            ByteArrayInputStream input = new ByteArrayInputStream(
                    matcher.group().getBytes(StandardCharsets.UTF_8.toString()));

            // parse the xml document
            Document doc = builder.parse(input);

            // remove all spaces
            NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET);
            // Remove each empty text node from document.
            for (int i = 0; i < emptyNodes.getLength(); i++) {
                Node emptyTextNode = emptyNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }

            // obtain researcher id
            String id = (String) idExpr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.isEmpty(id))
                throw new Exception("The record identifier can not be empty");

            // create record element
            Element record = oai.createElement("record");
            listRecords.appendChild(record);

            // create header element
            Element header = oai.createElement("header");
            record.appendChild(header);

            // create identifier element
            Element identifier = oai.createElement("identifier");
            identifier.setTextContent(id);
            header.appendChild(identifier);

            // create datestamp element
            Element datestamp = oai.createElement("datestamp");
            datestamp.setTextContent(date);
            header.appendChild(datestamp);

            // create set spec element if it exists
            if (!StringUtils.isEmpty(setSpecName)) {
                Element setSpec = oai.createElement("setSpec");
                setSpec.setTextContent(setSpecName);
                header.appendChild(setSpec);
            }

            // create metadata element
            Element metadata = oai.createElement("metadata");
            record.appendChild(metadata);

            // import the record
            metadata.appendChild(oai.importNode(doc.getDocumentElement(), true));
        }

        // create transformer factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create transformer
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

        if (formatOutput) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } else
            transformer.setOutputProperty(OutputKeys.INDENT, "no");

        // create dom source
        DOMSource oaiSource = new DOMSource(oai);

        // create stream result
        StreamResult result = new StreamResult(target.toFile());

        // stream xml to file
        transformer.transform(oaiSource, result);

        // optional stream xml to console for testing
        //StreamResult consoleResult = new StreamResult(System.out);
        //transformer.transform(oaiSource, consoleResult);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

        //e.printStackTrace();

        System.exit(1);
    }
}