List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.
This method is functionally equivalent to:
newInstance(DEFAULT_OBJECT_MODEL_URI)
Since the implementation for the W3C DOM is always available, this method will never fail.
From source file:com.betfair.testing.utils.cougar.assertions.AssertionUtils.java
public static void multiAssertEquals(Document expected, Document actual, String... unorderedXpaths) throws RuntimeException { try {/* w ww . ja va2 s. c o m*/ XPath xpath = XPathFactory.newInstance().newXPath(); for (String x : unorderedXpaths) { doDomSorting(expected, xpath, x); doDomSorting(actual, xpath, x); } } catch (XPathExpressionException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } jettAssertEquals(null, expected, actual); }
From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java
@Override protected AspectLexiconFactory addXmlPacket(AspectLexicon lexicon, InputStream input) throws ParserConfigurationException, SAXException, IOException, XPathException { Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon"); Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input"); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true);/*from ww w.ja v a 2 s .co m*/ Document doc = domFactory.newDocumentBuilder().parse(input); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if ("aspect".equalsIgnoreCase(doc.getDocumentElement().getLocalName())) { return this.addXmlAspect(lexicon, doc.getDocumentElement()); } Node lexiconNode = (Node) xpath.compile("/aspect-lexicon").evaluate(doc, XPathConstants.NODE); if (lexiconNode == null) { lexiconNode = Validate.notNull(doc.getDocumentElement(), CannedMessages.NULL_ARGUMENT, "/aspect-lexicon"); } String title = (String) xpath.compile("./@title").evaluate(lexiconNode, XPathConstants.STRING); String description = (String) xpath.compile("./@description").evaluate(lexiconNode, XPathConstants.STRING); if (StringUtils.isNotEmpty(title)) { lexicon.setTitle(title); } if (StringUtils.isNotEmpty(description)) { lexicon.setDescription(description); } return this.addXmlAspect(lexicon, lexiconNode); }
From source file:es.upv.grycap.coreutils.fiber.test.mockserver.ObjectResponseValidator.java
@Nullable private static String readObjectIdFromXml(final String payload) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(payload.getBytes())); final XPath xPath = XPathFactory.newInstance().newXPath(); final XPathExpression xPathExpression = xPath.compile("//*/coreutils/objectId/text()"); return trimToNull((String) xPathExpression.evaluate(document, STRING)); }
From source file:net.bulletin.pdi.xero.step.support.XMLChunkerTest.java
private void checkChunkForArtistDetails(String xml, String artistName, String[] genres) throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xPath = XPathFactory.newInstance().newXPath(); org.w3c.dom.Document doc = documentBuilder .parse(new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8))); Assert.assertEquals("the artist name does not match", artistName, xPath.evaluate("/Artist/Name", doc)); for (int i = 0; i < genres.length; i++) { Assert.assertEquals(genres[i], xPath.evaluate("/Artist/Genres/Genre[" + (i + 1) + "]", doc)); }/*from w ww.j a v a 2 s. com*/ }
From source file:au.edu.rmit.GalagoSearchClient.java
protected Document runSearchXML(String query, int count) throws ParserConfigurationException, UnsupportedEncodingException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); String baseURI = "http://" + host + ":" + Integer.toString(port) + "/searchxml"; String uri = baseURI + "?q=" + URLEncoder.encode(query, "UTF-8") + "&n=" + Integer.toString(count); Document result;//from www. j av a2s . c o m try { result = builder.parse(uri); } catch (Exception e) { e.printStackTrace(); result = builder.newDocument(); } return result; }
From source file:org.openhim.mediator.orchestration.RegistryActor.java
protected boolean isAdhocQuery(String msg) throws ParserConfigurationException, IOException, XPathExpressionException { try {/* w ww .j a v a2 s . co m*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(msg)); XPath xpath = XPathFactory.newInstance().newXPath(); String pathResult = xpath.compile("//AdhocQueryRequest[1]").evaluate(doc); return pathResult != null && !pathResult.isEmpty(); } catch (SAXException ex) { return false; } }
From source file:Main.java
/** * Gets the node list from the given xml file and the given xpath expression. * // w w w.jav a2 s. c om * @param xml * the xml file as string. * @param xpathExpression * the xpath expression as string. * @return the node list * @throws XPathExpressionException * the x path expression exception * @throws ParserConfigurationException * the parser configuration exception * @throws SAXException * the sAX exception * @throws IOException * Signals that an I/O exception has occurred. */ public static NodeList getNodeList(String xml, String xpathExpression) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(xml); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(xpathExpression); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; return nodes; }
From source file:com.seajas.search.contender.service.exploration.ExplorationService.java
/** * Make an attempt to retrieve all feed links from the given HTML content. * //www . j a v a2 s . co m * @param htmlContent * @return List<String> */ public List<String> getIndirectlyAccessibleFeedLinks(final URI uri, final String htmlContent) { List<String> result = new ArrayList<String>(); try { HtmlCleaner cleaner = new HtmlCleaner(); TagNode node = cleaner.clean(htmlContent); Document document = new CustomDomSerializer(cleaner.getProperties(), true).createDOM(node); // Now try to extract the appropriate links XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression xpathExpression = xpath.compile( "//head/link[contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'rss+xml') or contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'atom+xml')]/@href"); NodeList nodeList = (NodeList) xpathExpression.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node listNode = nodeList.item(i); if (listNode instanceof Attr) { String resultUrl = ((Attr) listNode).getValue(); if (!StringUtils.hasText(resultUrl)) { logger.warn("The given alternate-link tag contains no href - skipping"); continue; } try { new URL(resultUrl.trim()); result.add(resultUrl.trim()); } catch (MalformedURLException e) { try { result.add(uri.resolve(resultUrl.trim()).normalize().toString()); } catch (IllegalArgumentException e2) { logger.warn( "The given (presumably relative) URL is not valid - not adding to the result list", e2); } } } else logger.error("Invalid node type " + listNode.getNodeType() + " - skipping"); } } catch (XPathExpressionException e) { logger.error("Could not apply the given XPath expression to extract RSS alternate links", e); } // Now determine if the URLs are fully-qualified } catch (ParserConfigurationException e) { logger.info("Could not serialize the given content", e); return null; } return result; }
From source file:com.espertech.esper.event.xml.BaseXMLEventType.java
/** * Ctor.//from w w w . j a v a2 s. c o m * @param configurationEventTypeXMLDOM is the XML DOM configuration such as root element and schema names * @param metadata event type metadata * @param eventAdapterService for registration and lookup of types */ public BaseXMLEventType(EventTypeMetadata metadata, int eventTypeId, ConfigurationEventTypeXMLDOM configurationEventTypeXMLDOM, EventAdapterService eventAdapterService) { super(eventAdapterService, metadata, eventTypeId, Node.class); this.rootElementName = configurationEventTypeXMLDOM.getRootElementName(); this.configurationEventTypeXMLDOM = configurationEventTypeXMLDOM; xPathFactory = XPathFactory.newInstance(); if (configurationEventTypeXMLDOM.getXPathFunctionResolver() != null) { try { XPathFunctionResolver fresolver = (XPathFunctionResolver) JavaClassHelper.instantiate( XPathFunctionResolver.class, configurationEventTypeXMLDOM.getXPathFunctionResolver()); xPathFactory.setXPathFunctionResolver(fresolver); } catch (ClassInstantiationException ex) { throw new ConfigurationException("Error configuring XPath function resolver for XML type '" + configurationEventTypeXMLDOM.getRootElementName() + "' : " + ex.getMessage(), ex); } } if (configurationEventTypeXMLDOM.getXPathVariableResolver() != null) { try { XPathVariableResolver vresolver = (XPathVariableResolver) JavaClassHelper.instantiate( XPathVariableResolver.class, configurationEventTypeXMLDOM.getXPathVariableResolver()); xPathFactory.setXPathVariableResolver(vresolver); } catch (ClassInstantiationException ex) { throw new ConfigurationException("Error configuring XPath variable resolver for XML type '" + configurationEventTypeXMLDOM.getRootElementName() + "' : " + ex.getMessage(), ex); } } }
From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionDocumentFactory.java
private OpinionDocument create(OpinionDocument document, OpinionCorpus corpus, Node node) throws XPathException { try {/*from ww w . j a v a2 s . c o m*/ Validate.notNull(node, CannedMessages.NULL_ARGUMENT, "node"); } catch (NullPointerException e) { throw new IllegalFactoryOptionsException(e); } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Double polarity = (Double) xpath.compile("./@polarity").evaluate(node, XPathConstants.NUMBER); return this.create(document, corpus, node.getTextContent().trim(), polarity); }