List of usage examples for org.dom4j XPath valueOf
String valueOf(Object context);
valueOf
evaluates this XPath expression and returns the textual representation of the results using the XPath string() function. From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java
License:Open Source License
/** * Gets a the value as a string for the given XPath * * @param location Xpath to evaluate//from ww w.j av a 2s . com * @return The value */ @SuppressWarnings("unchecked") public String getPartAsString(Object location) throws MessageAccessException { if (!(location instanceof XPath)) { throw new MessageAccessException("Only XPath location's are supported for accessing XMLMessage parts - " + "received: " + location.getClass()); } XPath xpath = (XPath) location; String key = GET_PART_AS_STRING_KEY_PREFIX + xpath.getText(); if (getCache().containsKey(key)) { return (String) getCache().get(key); } else { String result = xpath.valueOf(getDocument()); // Do not do this - it does not evaluate expressions returning "false" // for example // String result = xpath.selectSingleNode(getDocument()).getText(); getCache().put(key, result); return result; } }
From source file:org.mule.module.xml.filters.JXPathFilter.java
License:Open Source License
private boolean accept(Object obj) { if (obj == null) { logger.warn("Applying JXPathFilter to null object."); return false; }// w ww . j av a 2s . com if (pattern == null) { logger.warn("Expression for JXPathFilter is not set."); return false; } if (expectedValue == null) { // Handle the special case where the expected value really is null. if (pattern.endsWith("= null") || pattern.endsWith("=null")) { expectedValue = "null"; pattern = pattern.substring(0, pattern.lastIndexOf("=")); } else { if (logger.isInfoEnabled()) { logger.info("Expected value for JXPathFilter is not set, using 'true' by default"); } expectedValue = Boolean.TRUE.toString(); } } Object xpathResult = null; boolean accept = false; Document dom4jDoc; try { dom4jDoc = XMLUtils.toDocument(obj, muleContext); } catch (Exception e) { logger.warn("JxPath filter rejected message because of an error while parsing XML: " + e.getMessage(), e); return false; } // Payload is XML if (dom4jDoc != null) { if (namespaces == null) { // no namespace defined, let's perform a direct evaluation xpathResult = dom4jDoc.valueOf(pattern); } else { // create an xpath expression with namespaces and evaluate it XPath xpath = DocumentHelper.createXPath(pattern); xpath.setNamespaceURIs(namespaces); xpathResult = xpath.valueOf(dom4jDoc); } } // Payload is a Java object else { if (logger.isDebugEnabled()) { logger.debug("Passing object of type " + obj.getClass().getName() + " to JXPathContext"); } JXPathContext context = JXPathContext.newContext(obj); initialise(context); xpathResult = context.getValue(pattern); } if (logger.isDebugEnabled()) { logger.debug("JXPathFilter Expression result = '" + xpathResult + "' - Expected value = '" + expectedValue + "'"); } // Compare the XPath result with the expected result. if (xpathResult != null) { accept = xpathResult.toString().equals(expectedValue); } else { // A null result was actually expected. if (expectedValue.equals("null")) { accept = true; } // A null result was not expected, something probably went wrong. else { logger.warn("JXPathFilter expression evaluates to null: " + pattern); } } if (logger.isDebugEnabled()) { logger.debug("JXPathFilter accept object : " + accept); } return accept; }
From source file:org.mule.module.xml.transformer.JXPathExtractor.java
License:Open Source License
/** * Evaluate the expression in the context of the given object and returns the * result. If the given object is a string, it assumes it is an valid xml and * parses it before evaluating the xpath expression. *//* w w w . ja v a 2 s . c o m*/ @Override public Object doTransform(Object src, String encoding) throws TransformerException { try { Object result = null; if (src instanceof String) { Document doc = DocumentHelper.parseText((String) src); XPath xpath = doc.createXPath(expression); if (namespaces != null) { xpath.setNamespaceURIs(namespaces); } // This is the way we always did it before, so keep doing it that way // as xpath.evaluate() will return non-string results (like Doubles) // for some scenarios. if (outputType == null && singleResult) { return xpath.valueOf(doc); } // TODO handle non-list cases, see //http://www.dom4j.org/apidocs/org/dom4j/XPath.html#evaluate(java.lang.Object) Object obj = xpath.evaluate(doc); if (obj instanceof List) { for (int i = 0; i < ((List) obj).size(); i++) { final Node node = (Node) ((List) obj).get(i); result = add(result, node); if (singleResult) { break; } } } else { result = add(result, obj); } } else { JXPathContext context = JXPathContext.newContext(src); result = context.getValue(expression); } return result; } catch (Exception e) { throw new TransformerException(this, e); } }
From source file:org.pentaho.di.trans.steps.getxmldata.GetXMLData.java
License:Apache License
private Object[] processPutRow(Node node) throws KettleException { // Create new row... Object[] outputRowData = buildEmptyRow(); // Create new row or clone if (meta.isInFields()) { System.arraycopy(data.readrow, 0, outputRowData, 0, data.nrReadRow); }/*from w w w . j a va 2 s . co m*/ try { data.nodenr++; // Read fields... for (int i = 0; i < data.nrInputFields; i++) { // Get field GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Get the Path to look for String XPathValue = xmlDataField.getResolvedXPath(); if (meta.isuseToken()) { // See if user use Token inside path field // The syntax is : @_Fieldname- // PDI will search for Fieldname value and replace it // Fieldname must be defined before the current node XPathValue = substituteToken(XPathValue, outputRowData); if (isDetailed()) { logDetailed(XPathValue); } } // Get node value String nodevalue; // Handle namespaces if (meta.isNamespaceAware()) { XPath xpathField = node.createXPath(addNSPrefix(XPathValue, data.PathValue)); xpathField.setNamespaceURIs(data.NAMESPACE); if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) { nodevalue = xpathField.valueOf(node); } else { // nodevalue=xpathField.selectSingleNode(node).asXML(); Node n = xpathField.selectSingleNode(node); if (n != null) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } else { if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) { nodevalue = node.valueOf(XPathValue); } else { // nodevalue=node.selectSingleNode(XPathValue).asXML(); Node n = node.selectSingleNode(XPathValue); if (n != null) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } // Do trimming switch (xmlDataField.getTrimType()) { case GetXMLDataField.TYPE_TRIM_LEFT: nodevalue = Const.ltrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_RIGHT: nodevalue = Const.rtrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_BOTH: nodevalue = Const.trim(nodevalue); break; default: break; } // Do conversions // ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(data.totalpreviousfields + i); ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(data.totalpreviousfields + i); outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData(sourceValueMeta, nodevalue); // Do we need to repeat this field if it is null? if (meta.getInputFields()[i].isRepeated()) { if (data.previousRow != null && Utils.isEmpty(nodevalue)) { outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields + i]; } } } // End of loop over fields... int rowIndex = data.totalpreviousfields + data.nrInputFields; // See if we need to add the filename to the row... if (meta.includeFilename() && !Utils.isEmpty(meta.getFilenameField())) { outputRowData[rowIndex++] = data.filename; } // See if we need to add the row number to the row... if (meta.includeRowNumber() && !Utils.isEmpty(meta.getRowNumberField())) { outputRowData[rowIndex++] = data.rownr; } // Possibly add short filename... if (meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0) { outputRowData[rowIndex++] = data.shortFilename; } // Add Extension if (meta.getExtensionField() != null && meta.getExtensionField().length() > 0) { outputRowData[rowIndex++] = data.extension; } // add path if (meta.getPathField() != null && meta.getPathField().length() > 0) { outputRowData[rowIndex++] = data.path; } // Add Size if (meta.getSizeField() != null && meta.getSizeField().length() > 0) { outputRowData[rowIndex++] = data.size; } // add Hidden if (meta.isHiddenField() != null && meta.isHiddenField().length() > 0) { outputRowData[rowIndex++] = Boolean.valueOf(data.path); } // Add modification date if (meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0) { outputRowData[rowIndex++] = data.lastModificationDateTime; } // Add Uri if (meta.getUriField() != null && meta.getUriField().length() > 0) { outputRowData[rowIndex++] = data.uriName; } // Add RootUri if (meta.getRootUriField() != null && meta.getRootUriField().length() > 0) { outputRowData[rowIndex] = data.rootUriName; } RowMetaInterface irow = getInputRowMeta(); if (irow == null) { data.previousRow = outputRowData; } else { // clone to previously allocated array to make sure next step doesn't // change it in between... System.arraycopy(outputRowData, 0, this.prevRow, 0, outputRowData.length); // Pick up everything else that needs a real deep clone data.previousRow = irow.cloneRow(outputRowData, this.prevRow); } } catch (Exception e) { if (getStepMeta().isDoingErrorHandling()) { // Simply add this row to the error row putError(data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001"); data.errorInRowButContinue = true; return null; } else { logError(e.toString()); throw new KettleException(e.toString()); } } return outputRowData; }
From source file:se.kb.xml.XPathWrapper.java
License:Apache License
/** * Selects the value of the given XPath. * /*from w ww . ja v a2s.c om*/ * @param xpathExpression the xpath * @return the value or <code>null</code> if no match */ public String valueOf(String xpathExpression) { XPath xpath = createXPath(xpathExpression); return xpath.valueOf(this.node); }