List of usage examples for javax.xml.xpath XPath compile
public XPathExpression compile(String expression) throws XPathExpressionException;
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 {//from w w w . jav a 2 s . c o m 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; }
From source file:fmiquerytest.Coordinates.java
private static List<String> getValueList(Document doc, XPath xpath, String expression) { List<String> list = new ArrayList<>(); try {/* ww w.ja v a2 s. com*/ //create XPathExpression object XPathExpression expr = xpath.compile(expression); //evaluate expression result on XML document NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); // NodeList nodeList = doc.getElementsByTagName("*"); // for (int i = 0; i < nodeList.getLength(); i++) { // Node node = nodeList.item(i); // if (node.getNodeType() == Node.ELEMENT_NODE) { // // do something with the current element // System.out.println(node.getNodeName()); // } // } for (int i = 0; i < nodes.getLength(); i++) { //System.out.println(nodes.item(i).getTextContent().trim()); list.add(nodes.item(i).getTextContent().trim()); } } catch (XPathExpressionException ex) { Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); } return list; }
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;/*w w w. j a va 2s. c o m*/ Object result; try { expr = xpath.compile(expression); result = expr.evaluate(responseDoc, type); } catch (XPathExpressionException e) { result = null; } return result; }
From source file:com.servicelibre.jxsl.scenario.test.xspec.XspecTestScenarioRunner.java
private void init() { XPath xpath = null; try {//from ww w. ja va 2 s . c om xpath = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON).newXPath(); } catch (XPathFactoryConfigurationException e1) { logger.error("Error while creating XPathFactory", e1); return; } SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); namespaceContext.bindNamespaceUri("x", "http://www.jenitennison.com/xslt/xspec"); xpath.setNamespaceContext(namespaceContext); try { successXpath = xpath.compile("count(//x:test[@successful ='false'] ) = 0"); testFailedCount = xpath.compile("count(//x:test[@successful ='false'] )"); testCount = xpath.compile("count(//x:test)"); } catch (XPathExpressionException e) { logger.error("Error while initializing {}.", this.getClass().getName(), e); } DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); try { xmlBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { logger.error("Error while configuring XML parser", e); } }
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 w w. j ava2s. c om*/ 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:ddf.catalog.test.TestCatalog.java
private String getMetacardIdFromCswInsertResponse(Response response) throws IOException, XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); String idPath = "//*[local-name()='identifier']/text()"; InputSource xml = new InputSource( IOUtils.toInputStream(response.getBody().asString(), StandardCharsets.UTF_8.name())); return xPath.compile(idPath).evaluate(xml); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
/** * @param acct//from w w w . j av a2 s . c om * @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:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java
private Map<String, String> identifyPreUpdateIdentifiers(String message) { Map<String, String> preUpdateIdentifiers = new HashMap<String, String>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*from w w w. jav a 2s . c o m*/ org.w3c.dom.Document doc = null; XPathExpression expr = null; XPathExpression exprIdType = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(new StringReader(message))); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); expr = xpath.compile("//preUpdateIdentifiers/preUpdateIdentifier/identifier/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); XPath xpathIdType = xFactory.newXPath(); exprIdType = xpathIdType.compile( "//preUpdateIdentifiers/preUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()"); Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; NodeList nodesIdType = (NodeList) resultIdType; for (int i = 0; i < nodes.getLength(); i++) { preUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return preUpdateIdentifiers; }
From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java
private Map<String, String> identifyPostUpdateIdentifiers(String message) { Map<String, String> postUpdateIdentifiers = new HashMap<String, String>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/* www .java 2 s. c om*/ org.w3c.dom.Document doc = null; XPathExpression expr = null; XPathExpression exprIdType = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(new StringReader(message))); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); expr = xpath.compile("//postUpdateIdentifiers/postUpdateIdentifier/identifier/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); XPath xpathIdType = xFactory.newXPath(); exprIdType = xpathIdType.compile( "//postUpdateIdentifiers/postUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()"); Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; NodeList nodesIdType = (NodeList) resultIdType; for (int i = 0; i < nodes.getLength(); i++) { postUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return postUpdateIdentifiers; }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParserTest.java
@Test public void testNamespaceAwareXpathResolveWithGenuineParser() throws Exception { NamespaceTestSuite testSuite = new NamespaceTestSuite().invoke(); DocumentBuilderFactory domFactory = testSuite.getDomFactory(); String xmlString = testSuite.getXmlString(); XPath xPath = testSuite.getxPath(); Map<String, String> namespaces = testSuite.getNamespaces(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document document = builder.parse(IOUtils.toInputStream(xmlString, Utils.UTF8)); XMLFromBinDataPreParser xmlFromBinDataPreParser = new XMLFromBinDataPreParser(); NamespaceMap nsContext = new NamespaceMap(); xPath.setNamespaceContext(nsContext); nsContext.addPrefixUriMappings(namespaces); NamespaceMap documentNamespaces = new NamespaceMap(); StreamsXMLUtils.resolveDocumentNamespaces(document, documentNamespaces, false); String evaluate = xPath.compile("/soapenv:Envelope/soapenv:Header/ch:TSYSprofileInq/ch:clientData") .evaluate(document);//from w ww . ja v a 2s .c om assertEquals("xxxxxx-343e-46af-86aa-634a3688cf30", evaluate); evaluate = xPath.compile("/Envelope/Header/TSYSprofileInq/clientData").evaluate(document); assertEquals("", evaluate); }