Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:com.bekwam.mavenpomupdater.MainViewController.java

private POMObject parseFile(String path) {

    if (log.isDebugEnabled()) {
        log.debug("[PARSE] path=" + path);
    }/*from  ww w .  jav  a2s .c om*/

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(path);

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expression = xpath.compile("//project/version/text()");
        Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

        String version = "";
        if (node != null) {
            version = node.getNodeValue();
            if (log.isDebugEnabled()) {
                log.debug("[PARSE]    version=" + node.getNodeValue());
            }
        }

        //           XPath pvXPath = XPathFactory.newInstance().newXPath();
        XPathExpression pvExpression = xpath.compile("//project/parent/version/text()");
        Node pvNode = (Node) pvExpression.evaluate(doc, XPathConstants.NODE);

        String pVersion = "";
        if (pvNode != null) {
            pVersion = pvNode.getNodeValue();
            if (log.isDebugEnabled()) {
                log.debug("[PARSE]    parentVersion=" + pvNode.getNodeValue());
            }
        }

        return new POMObject(true, path, version, pVersion, false);

    } catch (Exception exc) {
        log.error("error parsing path=" + path, exc);

        errorLogDelegate.log(path, exc.getMessage());

        return new POMObject(false, path, "Parse Error (will be skipped)", "Parse Error (will be skipped)",
                true);
    }
}

From source file:dk.netarkivet.harvester.harvesting.WARCWriterProcessor.java

/**
 * Return relevant values as header-like fields (here ANVLRecord, but spec-defined "application/warc-fields" type
 * when written). Field names from from DCMI Terms and the WARC/0.17 specification.
 *
 * @see org.archive.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 *//*www.  j a  va2 s  . co m*/
@Override
protected String getFirstrecordBody(File orderFile) {
    ANVLRecord record = new ANVLRecord(7);
    record.addLabelValue("software", "Heritrix/" + Heritrix.getVersion() + " http://crawler.archive.org");

    try {
        InetAddress host = InetAddress.getLocalHost();
        record.addLabelValue("ip", host.getHostAddress());
        record.addLabelValue("hostname", host.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }

    // conforms to ISO 28500:2009 as of May 2009
    // as described at http://bibnum.bnf.fr/WARC/
    // latest draft as of November 2008
    record.addLabelValue("format", "WARC File Format 1.0");
    record.addLabelValue("conformsTo", "http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf");

    // Get other values from order.xml
    try {
        Document doc = XmlUtils.getDocument(orderFile);
        addIfNotBlank(record, "operator", XmlUtils.xpathOrNull(doc, "//meta/operator"));
        addIfNotBlank(record, "publisher", XmlUtils.xpathOrNull(doc, "//meta/organization"));
        addIfNotBlank(record, "audience", XmlUtils.xpathOrNull(doc, "//meta/audience"));
        addIfNotBlank(record, "isPartOf", XmlUtils.xpathOrNull(doc, "//meta/name"));

        // disabling "created" field per HER-1634
        // though it's theoretically useful as a means of distinguishing
        // one crawl from another, the current usage/specification is too
        // vague... in particular a 'created' field in the 'warcinfo' is
        // reasonable to interpret as applying to the WARC-unit, rather
        // than the crawl-job-unit so we remove it and see if anyone
        // complains or makes a case for restoring it in a less-ambiguous
        // manner
        // String rawDate = XmlUtils.xpathOrNull(doc,"//meta/date");
        // if(StringUtils.isNotBlank(rawDate)) {
        // Date date;
        // try {
        // date = ArchiveUtils.parse14DigitDate(rawDate);
        // addIfNotBlank(record,"created",ArchiveUtils.getLog14Date(date));
        // } catch (ParseException e) {
        // logger.log(Level.WARNING,"obtaining warc created date",e);
        // }
        // }

        addIfNotBlank(record, "description", XmlUtils.xpathOrNull(doc, "//meta/description"));
        addIfNotBlank(record, "robots",
                XmlUtils.xpathOrNull(doc, "//newObject[@name='robots-honoring-policy']/string[@name='type']"));
        addIfNotBlank(record, "http-header-user-agent",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='user-agent']"));
        addIfNotBlank(record, "http-header-from",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='from']"));
        if (metadataMap == null) {
            //metadataMap = getMetadataItems();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(H1HeritrixTemplate.METADATA_ITEMS_XPATH);
            Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
            //NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            //Node node = nodeList.item(0);
            if (node != null) {
                NodeList nodeList = node.getChildNodes();
                if (nodeList != null) {
                    metadataMap = new HashMap();
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        node = nodeList.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            String typeName = node.getNodeName();
                            if ("string".equals(typeName)) {
                                Node attribute = node.getAttributes().getNamedItem("name");
                                if (attribute != null && attribute.getNodeType() == Node.ATTRIBUTE_NODE) {
                                    String key = attribute.getNodeValue();
                                    if (key != null && key.length() > 0) {
                                        String value = node.getTextContent();
                                        metadataMap.put(key, value);
                                        // debug
                                        //System.out.println(key + "=" + value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, "Error obtaining warcinfo", e);
    } catch (XPathExpressionException e) {
        logger.log(Level.WARNING, "Error obtaining metadata items", e);
    }

    // add fields from harvesInfo.xml version 0.4
    /*
     * <harvestInfo> <version>0.4</version> <jobId>1</jobId> <priority>HIGHPRIORITY</priority>
     * <harvestNum>0</harvestNum> <origHarvestDefinitionID>1</origHarvestDefinitionID>
     * <maxBytesPerDomain>500000000</maxBytesPerDomain> <maxObjectsPerDomain>2000</maxObjectsPerDomain>
     * <orderXMLName>default_orderxml</orderXMLName>
     * <origHarvestDefinitionName>netarkivet</origHarvestDefinitionName> <scheduleName>Once_a_week</scheduleName>
     * <harvestFilenamePrefix>1-1</harvestFilenamePrefix> <jobSubmitDate>Some date</jobSubmitDate>
     * <performer>undefined</performer> </harvestInfo>
     */
    String netarchiveSuiteComment = "#added by NetarchiveSuite "
            + dk.netarkivet.common.Constants.getVersionString();
    ANVLRecord recordNAS = new ANVLRecord(7);

    if (metadataMap != null) {
        // Add the data from the metadataMap to the WarcInfoRecord.
        recordNAS.addLabelValue(HARVESTINFO_VERSION, (String) metadataMap.get(HARVESTINFO_VERSION));
        recordNAS.addLabelValue(HARVESTINFO_JOBID, (String) metadataMap.get(HARVESTINFO_JOBID));
        recordNAS.addLabelValue(HARVESTINFO_CHANNEL, (String) metadataMap.get(HARVESTINFO_CHANNEL));
        recordNAS.addLabelValue(HARVESTINFO_HARVESTNUM, (String) metadataMap.get(HARVESTINFO_HARVESTNUM));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONID,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONID));
        recordNAS.addLabelValue(HARVESTINFO_MAXBYTESPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXBYTESPERDOMAIN));

        recordNAS.addLabelValue(HARVESTINFO_MAXOBJECTSPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXOBJECTSPERDOMAIN));
        recordNAS.addLabelValue(HARVESTINFO_ORDERXMLNAME, (String) metadataMap.get(HARVESTINFO_ORDERXMLNAME));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONNAME,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONNAME));

        if (metadataMap.containsKey((HARVESTINFO_SCHEDULENAME))) {
            recordNAS.addLabelValue(HARVESTINFO_SCHEDULENAME,
                    (String) metadataMap.get(HARVESTINFO_SCHEDULENAME));
        }
        recordNAS.addLabelValue(HARVESTINFO_HARVESTFILENAMEPREFIX,
                (String) metadataMap.get(HARVESTINFO_HARVESTFILENAMEPREFIX));

        recordNAS.addLabelValue(HARVESTINFO_JOBSUBMITDATE, (String) metadataMap.get(HARVESTINFO_JOBSUBMITDATE));

        if (metadataMap.containsKey(HARVESTINFO_PERFORMER)) {
            recordNAS.addLabelValue(HARVESTINFO_PERFORMER, (String) metadataMap.get(HARVESTINFO_PERFORMER));
        }

        if (metadataMap.containsKey(HARVESTINFO_AUDIENCE)) {
            recordNAS.addLabelValue(HARVESTINFO_AUDIENCE, (String) metadataMap.get(HARVESTINFO_AUDIENCE));
        }
    } else {
        logger.log(Level.SEVERE, "Error missing metadata");
    }

    // really ugly to return as string, when it may just be merged with
    // a couple other fields at write time, but changing would require
    // larger refactoring
    return record.toString() + netarchiveSuiteComment + "\n" + recordNAS.toString();
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private Object evaluate(Document responseDoc, String expression, QName type) {
    if (responseDoc == null)
        return null;
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr;
    Object result;//  w  ww  .j  av a  2  s. co  m
    try {
        expr = xpath.compile(expression);
        result = expr.evaluate(responseDoc, type);
    } catch (XPathExpressionException e) {
        result = null;
    }

    return result;
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 * @param acct//w ww. j a va2  s.c o m
 * @param UID - null or empty if don't care
 * @param expected - false if don't expect a matching item to be in collection within timeout time
 * @return href of first matching item found
 * @throws ServiceException
 * @throws IOException
 */
public static String waitForItemInCalendarCollectionByUID(String url, Account acct, String UID,
        boolean expected, int timeout_millis) throws ServiceException, IOException {
    int orig_timeout_millis = timeout_millis;
    while (timeout_millis > 0) {
        Document doc = calendarQuery(url, acct);
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
        XPathExpression xPathExpr;
        try {
            xPathExpr = xpath.compile("/D:multistatus/D:response/D:href/text()");
            NodeList result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
            if (1 <= result.getLength()) {
                for (int ndx = 0; ndx < result.getLength(); ndx++) {
                    Node item = result.item(ndx);
                    String nodeValue = item.getNodeValue();
                    if ((Strings.isNullOrEmpty(UID)) || (nodeValue.contains(UID))) {
                        if (!expected) {
                            fail(String.format(
                                    "item with UID '%s' unexpectedly arrived in collection '%s' within %d millisecs",
                                    Strings.nullToEmpty(UID), url, orig_timeout_millis - timeout_millis));

                        }
                        return nodeValue;
                    }
                }
            }
        } catch (XPathExpressionException e1) {
            ZimbraLog.test.debug("xpath problem", e1);
        }
        try {
            if (timeout_millis > TestUtil.DEFAULT_WAIT) {
                Thread.sleep(TestUtil.DEFAULT_WAIT);
                timeout_millis = timeout_millis - TestUtil.DEFAULT_WAIT;
            } else {
                Thread.sleep(timeout_millis);
                timeout_millis = 0;

            }
        } catch (InterruptedException e) {
            ZimbraLog.test.debug("sleep got interrupted", e);
        }
    }
    if (expected) {
        fail(String.format("item with UID '%s' didn't arrive in collection '%s' within %d millisecs",
                Strings.nullToEmpty(UID), url, orig_timeout_millis));
    }
    return null;

}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static Document groupMemberSetExpandProperty(Account acct, Account member, boolean proxyWrite)
        throws IOException, ServiceException {
    String url = proxyWrite ? TestCalDav.getCalendarProxyWriteUrl(acct)
            : TestCalDav.getCalendarProxyReadUrl(acct);
    url = url.replaceAll("@", "%40");
    String href = proxyWrite ? UrlNamespace.getCalendarProxyWriteUrl(acct, acct)
            : UrlNamespace.getCalendarProxyReadUrl(acct, acct);
    href = href.replaceAll("@", "%40");
    ReportMethod method = new ReportMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(TestCalDav.expandPropertyGroupMemberSet.getBytes(),
            MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    try {//ww w .ja v  a2s . c  om
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for response", href, text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/D:group-member-set/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharee", UrlNamespace.getPrincipalUrl(member).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    return doc;
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

public void doUpdate() {

    for (POMObject p : tblPOMS.getItems()) {

        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] p=" + p.getAbsPath());
        }/*from  w ww.  java  2 s .  c  o m*/

        if (p.getParseError()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because of a parse error on scanning");
            }
            continue;
        }

        if (!p.getUpdate()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because user excluded it from update");
            }
            continue;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(p.getAbsPath());

            if (p.getParentVersion() != null && p.getParentVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/parent/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getParentVersion());
                }
            }

            if (p.getVersion() != null && p.getVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getVersion());
                }
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            String workingFileName = p.getAbsPath() + ".mpu";
            FileWriter fw = new FileWriter(workingFileName);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fw);
            transformer.transform(source, result);
            fw.close();

            Path src = FileSystems.getDefault().getPath(workingFileName);
            Path target = FileSystems.getDefault().getPath(p.getAbsPath());

            Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);

            Files.delete(src);

        } catch (Exception exc) {
            log.error("error updating poms", exc);
        }
    }

    if (StringUtils.isNotEmpty(tfRootDir.getText())) {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] issuing rescan command");
        }
        scan();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] did an update, but there is not value in root; clearing");
        }
        tblPOMS.getItems().clear();
    }
    tblPOMSDirty = false;
    tfNewVersion.setDisable(false);
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Extract a tracking ID from an XML string.
 * // w ww .ja v a  2  s . c  o m
 * @param xml
 *        the XML to extract from
 * @param xp
 *        the XPath to use that returns a number
 * @param xpath
 *        the XPath as a string (for debugging)
 * @return the tracking ID, or <em>null</em> if not found
 */
protected Long extractTrackingId(InputSource xml, XPathExpression xp, String xpath) {
    Double tid;
    try {
        tid = (Double) xp.evaluate(xml, XPathConstants.NUMBER);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
    if (tid.isNaN()) {
        log.warn("Unable to extract tracking ID via XPath [{}]", xpath);
        return null;
    }
    return tid.longValue();
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

public Map<String, UniverseNodeInfo> getUniverseNodesInfo(String token, String universeName)
        throws UniverseException {
    UniverseInfo universeInfo = universesMap.get(universeName);
    if (universeInfo != null && StringUtils.isNotBlank(universeInfo.getId())) {
        Map<String, UniverseNodeInfo> universeNodeInfoMap = universeInfosMap.get(universeName);
        if (universeNodeInfoMap != null && universesInfoUpdatedMap.containsKey(universeName)
                && !isExpired(universesInfoUpdatedMap.get(universeName))) {
            return universeNodeInfoMap;
        } else {//from  w w  w.  j  av  a2  s . c  om
            universeNodeInfoMap = new HashMap<>();
        }
        try {
            HttpGet httpGet = new HttpGet(
                    String.format("%s%s%s", apiUrl, "/sl/v1/universes/", universeInfo.getId()));
            setHeaders(httpGet, token);
            HttpResponse response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200) {
                try (InputStream xmlStream = response.getEntity().getContent()) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(xmlStream);
                    XPathFactory xPathfactory = XPathFactory.newInstance();
                    XPath xpath = xPathfactory.newXPath();
                    XPathExpression expr = xpath.compile("//outline/folder");
                    XPathExpression exprRootItems = xpath.compile("//outline/item");
                    NodeList universeInfoNodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                    NodeList universeRootInfoNodes = (NodeList) exprRootItems.evaluate(doc,
                            XPathConstants.NODESET);
                    if (universeInfoNodes != null) {
                        parseUniverseInfo(universeInfoNodes, universeNodeInfoMap);
                    }
                    if (universeRootInfoNodes != null) {
                        parseUniverseInfo(universeRootInfoNodes, universeNodeInfoMap);
                    }
                } catch (Exception e) {
                    throw new UniverseException(String.format(errorMessageTemplate,
                            "UniverseClient " + "(get universe nodes info): Response processing failed",
                            ExceptionUtils.getStackTrace(e)));
                }
            }
        } catch (IOException e) {
            throw new UniverseException(String.format(errorMessageTemplate,
                    "UniverseClient " + "(get universe nodes info): Request failed",
                    ExceptionUtils.getStackTrace(e)));
        }
        universeInfosMap.put(universeName, universeNodeInfoMap);
        universesInfoUpdatedMap.put(universeName, System.currentTimeMillis());

        return universeNodeInfoMap;
    }
    return Collections.emptyMap();

}

From source file:com.rest4j.generator.Generator.java

List<ModelNode> computeModelGraph(Document xml) throws Exception {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    xpath.setNamespaceContext(new APINamespaceContext());
    XPathExpression refsExpr = xpath.compile(".//api:complex");
    HashMap<String, ModelNode> graph = new HashMap<String, ModelNode>();
    for (Node model : Util.it(xml.getDocumentElement().getElementsByTagName("model"))) {
        String name = ((Attr) model.getAttributes().getNamedItem("name")).getValue();
        graph.put(name, new ModelNode(model));
    }/*  w  w w .  ja  v  a  2 s  .  c  om*/
    for (ModelNode node : graph.values()) {
        for (Node complex : Util.it((NodeList) refsExpr.evaluate(node.model, XPathConstants.NODESET))) {
            Ref ref = new Ref();
            String type = complex.getAttributes().getNamedItem("type").getTextContent();
            ModelNode referenced = graph.get(type);
            if (referenced == null)
                throw new IllegalArgumentException("Wrong reference from "
                        + node.model.getAttributes().getNamedItem("name").getTextContent() + "."
                        + complex.getAttributes().getNamedItem("name").getTextContent() + " to " + type);
            ref.referencedModel = referenced;
            if (complex.getAttributes().getNamedItem("collection").getTextContent().equals("array")) {
                ref.array = true;
            }
            node.references.add(ref);
        }
    }
    return new ArrayList<ModelNode>(graph.values());
}

From source file:betullam.xmlmodifier.XMLmodifier.java

private List<Element> getElementsForInsertion(String condStructureElements, Document xmlDoc) {

    List<Element> elementsForInsertion = new ArrayList<Element>();
    List<String> dmdLogIds = new ArrayList<String>();
    List<String> structureElements = Arrays.asList(condStructureElements.split("\\s*,\\s*"));
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression;

    // First, get all DMDLOG-IDs from the structMap-Node:
    for (String structureElement : structureElements) {

        try {/*w  w  w  .ja  va2s. c om*/
            xPathExpression = xPath
                    .compile("//mets/structMap[@TYPE='LOGICAL']//div[@TYPE='" + structureElement + "']");
            NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDoc, XPathConstants.NODESET);

            if (nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    if (nodeList.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                        Element structMapElement = (Element) nodeList.item(i);
                        String dmdLogId = (!structMapElement.getAttribute("DMDID").isEmpty())
                                ? structMapElement.getAttribute("DMDID")
                                : null;
                        if (dmdLogId != null) {
                            dmdLogIds.add(dmdLogId);
                        }
                    }
                }
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

    // Now get all subnodes of the mets:dmdSec nodes with the right ID where we want to insert the new element:
    for (String dmdLogId : dmdLogIds) {
        try {
            if (isModsMets(xmlDoc) == true) {
                xPathExpression = xPath.compile("//mets/dmdSec[@ID='" + dmdLogId + "']/mdWrap/xmlData/mods");
            } else {
                xPathExpression = xPath
                        .compile("//mets/dmdSec[@ID='" + dmdLogId + "']/mdWrap/xmlData/mods/extension/goobi");
            }
            NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDoc, XPathConstants.NODESET);
            if (nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    if (nodeList.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                        Element elementForInsertion = (Element) nodeList.item(i);
                        elementsForInsertion.add(elementForInsertion);
                    }
                }
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

    return elementsForInsertion;

}