public WikipediaConfig() throws XPathExpressionException { contentPath = xpath.compile(ConfigDefaults.XPATH_CONTENT); descriptionPath = xpath.compile(ConfigDefaults.XPATH_DESCRIPTION); redirectPath = xpath.compile(ConfigDefaults.XPATH_REDIRECT_URL); referencesPath = xpath.compile(ConfigDefaults.XPATH_REFERENCES); referenceUrlPath = xpath.compile(ConfigDefaults.XPATH_REFERENCE_URL); }
@Override public void run() { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final XPath xPath = XPathFactory.newInstance().newXPath(); final String expression = "//" + TAG_TRACK_POINT; final String speedExpression = "//" + TAG_SPEED; NodeList nodeList = null; NodeList speedList = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(traceFile); nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET); speedList = (NodeList) xPath.compile(speedExpression).evaluate(document, XPathConstants.NODESET); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } parse(nodeList, speedList); }
public List<String> getOriginCatalogs() { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); List<String> catalogs = new ArrayList<String>(); try { XPathExpression expr = xpath.compile("//Resolver"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { XPathExpression hasAliasExp = xpath.compile("./alias"); NodeList aliases = (NodeList) hasAliasExp.evaluate(nodes.item(i), XPathConstants.NODESET); if (aliases.getLength() > 0) { XPathExpression nameAttribute = xpath.compile("@name"); String name = (String) nameAttribute.evaluate(nodes.item(i), XPathConstants.STRING); catalogs.add(name); } } } catch (XPathExpressionException e) { e.printStackTrace(); } return catalogs; }
public Location getLocationData() { Location location = new Location(); try { LocationDoc = builder.parse(new FileInputStream("location.xml")); String ExtendedNameExpression = "/GeocodeResponse/result/formatted_address/text()"; String LatitudeExpression = "/GeocodeResponse/result/geometry/location/lat/text()"; String LongitudeExpression = "/GeocodeResponse/result/geometry/location/lng/text()"; String ShortNameExpression = "/GeocodeResponse/result/address_component/short_name/text()"; XPath xPath = XPathFactory.newInstance().newXPath(); // read a string value location.setExtendedName(xPath.compile(ExtendedNameExpression).evaluate(LocationDoc)); location.setLatitude( Float.parseFloat(xPath.compile(LatitudeExpression).evaluate(LocationDoc))); location.setLongitude( Float.parseFloat(xPath.compile(LongitudeExpression).evaluate(LocationDoc))); location.setName(xPath.compile(ShortNameExpression).evaluate(LocationDoc)); // read an xml node using xpath } catch (Exception ex) { Logger.getLogger(DataFiller.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(location); return location; }
{ try { appletClassXPression = xPath.compile("/applet-app/applet/applet-class/text()"); // NOI18N appletAIDXPression = xPath.compile("/applet-app/applet/applet-AID/text()"); // NOI18N } catch (XPathExpressionException e) { Exceptions.printStackTrace(e); } }
{ try { linksXPath = xpath.compile("//a/@href"); scriptXPath = xpath.compile("//head/script/@src"); imgsXPath = xpath.compile("//img/@src"); } catch (XPathExpressionException e) { // will only occur if a bug prevents class from loading // should never occur if class passes ANY unit test throw new AssertionError("Shouldn't get here", e); } }
public LFParseEnricher() { XPathFactory factory = XPathFactory.newInstance(); xpath = factory.newXPath(); try { theoryXPath = xpath.compile("//theory"); viewXPath = xpath.compile("//view"); viewXPath = xpath.compile("//include"); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void reportAndVerify(String conceptName, int assertedEdges) throws Exception { Document doc = scanAndWriteReport(conceptName, TestClass.class); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression classExpression = xpath.compile("/graphml/graph/node[contains(@labels,':Class')]/data[@key='fqn']"); String fqn = classExpression.evaluate(doc); assertThat(fqn, equalTo(TestClass.class.getName())); XPathExpression declaresExpression = xpath.compile("//edge"); NodeList edges = (NodeList) declaresExpression.evaluate(doc, XPathConstants.NODESET); assertThat(edges.getLength(), equalTo(assertedEdges)); }
static { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); try { tokenIdExpression = xpath.compile("/access/token/@id"); publicUrlExpression = xpath.compile( "/access/serviceCatalog/service[@type='object-store']/endpoint/@publicURL"); } catch (XPathExpressionException e) { // Do nothing } }
// CreateShortcut, LoadResource, InitDiagramFileAction public void testPredefinedActions() throws Exception { DiaGenSource s1 = createLibraryGen(false); final GenEditorGenerator editorGen = s1.getGenDiagram().getEditorGen(); GenContextMenu menu = GMFGenFactory.eINSTANCE.createGenContextMenu(); menu.getContext().add(s1.getGenDiagram()); final CreateShortcutAction createShortcutAction = GMFGenFactory.eINSTANCE.createCreateShortcutAction(); final LoadResourceAction loadResourceAction = GMFGenFactory.eINSTANCE.createLoadResourceAction(); menu.getItems().add(createShortcutAction); menu.getItems().add(loadResourceAction); editorGen.getContextMenus().clear(); // make sure there's no other (default) menus editorGen.getContextMenus().add(menu); editorGen.getDiagram().getContainsShortcutsTo().add("ecore"); assertTrue("sanity", editorGen.getDiagram().generateCreateShortcutAction()); // generateAndCompile(s1); // IProject generatedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(editorGen.getPlugin().getID()); IFile generatedManifest = generatedProject.getFile("plugin.xml"); assertTrue(generatedManifest.exists()); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document parsedManifest = db.parse(new InputSource(generatedManifest.getContents())); XPath xf = XPathFactory.newInstance().newXPath(); XPathExpression xe = xf.compile("/plugin/extension[@point = 'org.eclipse.ui.menus']/menuContribution/command"); NodeList result = (NodeList) xe.evaluate(parsedManifest, XPathConstants.NODESET); assertEquals(2, result.getLength()); xe = xf.compile("/plugin/extension[@point = 'org.eclipse.ui.commands']/command"); result = (NodeList) xe.evaluate(parsedManifest, XPathConstants.NODESET); assertTrue(result.getLength() > 2); HashSet<String> allCommands = new HashSet<String>(); for (int i = result.getLength() - 1; i >= 0; i--) { allCommands.add(result.item(i).getAttributes().getNamedItem("defaultHandler").getNodeValue()); } assertTrue(allCommands.contains(createShortcutAction.getQualifiedClassName())); assertTrue(allCommands.contains(loadResourceAction.getQualifiedClassName())); IFile file1 = generatedProject.getFile( "/src/" + createShortcutAction.getQualifiedClassName().replace('.', '/') + ".java"); IFile file2 = generatedProject.getFile( "/src/" + loadResourceAction.getQualifiedClassName().replace('.', '/') + ".java"); assertTrue(file1.exists()); assertTrue(file2.exists()); // // DiaGenSource s2 = createLibraryGen(true); // fail("TODO"); }
/** * Returns a list of ref nodes from the ref-list of the DOM. * * @param doc DOM representation of the XML * @return NodeList of ref elements * @throws XPathExpressionException */ private NodeList getReferenceNodes(Document doc) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//back/ref-list[title='References']/ref"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList refList = (NodeList) result; if (refList.getLength() == 0) { expr = xpath.compile("//back/ref-list/ref"); result = expr.evaluate(doc, XPathConstants.NODESET); refList = (NodeList) result; } return refList; }
private String handleResponse(HttpResponse httpResponse) throws IOException { final int ok = 200; if (httpResponse.getStatusLine().getStatusCode() == ok) { String reply = IOUtils.toString(httpResponse.getEntity().getContent()); if (reply == null) { LOGGER.error("Http request failed. Service did not respond."); return "-"; } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(reply.getBytes())); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/calendarItems/status/text()"); String status = expr.evaluate(doc); if ("PROCESSED".equals(status)) { String res = xpath.compile("/calendarItems/total/text()").evaluate(doc); return res; } else { return ""; // The user does not have any notes calendar and should receive nothing. } } catch (RuntimeException ex) { LOGGER.warn(ex.getMessage()); } catch (ParserConfigurationException e) { LOGGER.warn(e.getMessage()); } catch (SAXException e) { LOGGER.warn(e.getMessage()); } catch (XPathExpressionException e) { LOGGER.warn(e.getMessage()); } return "-"; } else { LOGGER.error( "Http request failed. Response code=" + httpResponse.getStatusLine().getStatusCode() + ". " + httpResponse.getStatusLine().getReasonPhrase()); return "-"; } }
private Integer fromCitation(Document doc, XPath xpath) { try { XPathExpression expr = xpath.compile("//p"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Node classNode = node.getAttributes().getNamedItem("class"); if (classNode == null) continue; String pClass = classNode.getTextContent(); if (pClass.equalsIgnoreCase("case_cite")) { String citationString = node.getTextContent(); Matcher citationYearMatcher = citationYearPattern.matcher(citationString); boolean foundDate = citationYearMatcher.matches(); if (foundDate) { String yearString = citationYearMatcher.group(1).toString(); return Integer.parseInt(yearString); } } } } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Takes an XML file containing parameterised queries + parameter queries and substitutes * parameters for values, then saves the resulting queries * * @param queryFileName the XML query file * @param queryMixFile * @param ignoreFile */ public void generateQueries(String queryFileName, String queryMixFile, String ignoreFile) { File queryFile = new File(queryFileName); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(queryFile); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("/queries/query"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; // for each query, generate a map of parameter names and values // then replace the parameters in the final query with the respective (randomly // selected) values for (int i = 0; i < nodes.getLength(); i++) { queryCount = i + 1; String completeQuery = generateCompleteQuery(nodes.item(i), doc); saveCompleteQuery(completeQuery); } saveHelperFiles(queryMixFile, ignoreFile); } catch (Exception e) { e.printStackTrace(); } }
/** * Get container window * * <p> * * @return String */ private String getWindowName(String sWidgetID) { String sWindowName = null; // get widget ID XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr; Object result; NodeList nodes; try { String xpathExpression = "/GUIStructure/GUI[Container//Property[Name=\"" + GUITARConstants.ID_TAG_NAME + "\" and Value=\"" + sWidgetID + "\"]]/Window/Attributes/Property[Name=\"" + GUITARConstants.TITLE_TAG_NAME + "\"]/Value/text()"; expr = xpath.compile(xpathExpression); result = expr.evaluate(docGUI, XPathConstants.NODESET); nodes = (NodeList) result; if (nodes.getLength() > 0) sWindowName = nodes.item(0).getNodeValue(); } catch (XPathExpressionException e) { GUITARLog.log.error(e); } return sWindowName; }
@Override public void addAssociation( String associationName, String workflowId, String eventId, String condition) throws WorkflowException { if (StringUtils.isBlank(workflowId)) { log.error("Null or empty string given as workflow id to be associated to event."); throw new InternalWorkflowException("Service alias cannot be null"); } if (StringUtils.isBlank(eventId)) { log.error("Null or empty string given as 'event' to be associated with the service."); throw new InternalWorkflowException("Event type cannot be null"); } if (StringUtils.isBlank(condition)) { log.error( "Null or empty string given as condition expression when associating " + workflowId + " to event " + eventId); throw new InternalWorkflowException("Condition cannot be null"); } // check for xpath syntax errors XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { xpath.compile(condition); workflowDAO.addAssociation(associationName, workflowId, eventId, condition); } catch (XPathExpressionException e) { log.error("The condition:" + condition + " is not an valid xpath expression.", e); throw new WorkflowRuntimeException("The condition is not a valid xpath expression."); } }
public static void main(String[] args) { CodeExtractor myCode = new CodeExtractor(4); // myCode.parseFile("http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html"); myCode.parseFile("http://www.javadeveloper.co.in/java-example/java-hashmap-example.html"); String docString = myCode.getDoc(); try { XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression nodeXPathExpr = xPath.compile("/codesnippets/text | /codesnippets/sourcecode"); InputSource inputSource = new InputSource(new ByteArrayInputStream(docString.getBytes())); NodeList allNodes = (NodeList) nodeXPathExpr.evaluate(inputSource, XPathConstants.NODESET); int nodeNumber = allNodes.getLength(); System.out.println("Text Found:: " + nodeNumber + " nodes."); System.out.println("========================================"); for (int i = 0; i < nodeNumber; i++) { Node node = allNodes.item(i); String content = node.getTextContent(); // content = StringEscapeUtils.unescapeHtml(content).trim(); System.out.println(node + ":--->:" + node.getNodeName()); if (node.getTextContent() != null) System.out.println("--->" + content); System.out.println("========================================"); } } catch (XPathExpressionException e) { e.printStackTrace(); } }
public static void readXpath() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("D:\\temp\\test_2\\screen_2.xml"); XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value // XPathExpression expr = xpath // .compile("//Screens/Screen[@number='1']/Button[@number='1']/Action[@type='onclick']/*"); String xpathStr = "//Screen[@number='2007']/Button[@number='87'][@h='1']"; XPathExpression expr = xpath.compile(xpathStr); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { NamedNodeMap nodeMap = nodes.item(i).getAttributes(); String attrName = ""; for (int j = 0; j < nodeMap.getLength(); j++) { attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("=")); if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) { System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue()); } } } }
/** * Evaluate an XPath string and return true if the output is to be included or not. * * @param contextNode The node to start searching from. * @param xpathnode The XPath node * @param str The XPath expression * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. */ public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) throws TransformerException { if (!str.equals(xpathStr) || xpathExpression == null) { if (xpf == null) { xpf = XPathFactory.newInstance(); try { xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (XPathFactoryConfigurationException ex) { throw new TransformerException(ex); } } XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); xpathStr = str; try { xpathExpression = xpath.compile(xpathStr); } catch (XPathExpressionException ex) { throw new TransformerException(ex); } } try { return (Boolean) xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); } catch (XPathExpressionException ex) { throw new TransformerException(ex); } }
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { DocumentBuilder bud = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream inp = new ByteArrayInputStream(xml.getBytes()); Document doc = bud.parse(inp); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//Person/PostalCode"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getTextContent()); nodes.item(i).setTextContent("Ala ma kota " + i); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); StringWriter bufor = new StringWriter(); xformer.transform(new DOMSource(doc), new StreamResult(bufor)); System.out.println("==================="); System.out.println(bufor.toString()); }
private String fromXmlToColor(String xml) { String result = BLUE; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = null; try { builder = domFactory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xml))); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//color"); Object n = expr.evaluate(document, XPathConstants.NODESET); NodeList nodes = (NodeList) n; if (nodes.getLength() > 0) { result = (String) nodes.item(0).getTextContent(); } } catch (Exception e) { System.err.println("fromXmlToColor:" + e); } return result; }
public NodeList getHeaderRows() throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // docFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); NodeList sheetLst = doc.getElementsByTagName("ss:Name"); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//Worksheet[@Name=\"" + sheetName + "\"]/Table/Row[1]/Cell"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList headerNodes = (NodeList) result; Node toRem = (Node) headerNodes.item(0); for (int i = 0; i < sheetLst.getLength(); i++) { List lstFields = new ArrayList<Node>(); List lstFields_common = new ArrayList<Node>(); log.debug("======================start======================="); Node testSuiteNode = sheetLst.item(i); NamedNodeMap commonAttributesList = testSuiteNode.getAttributes(); } return headerNodes; }
public Object resolveReference( Object referencedObject, Node elementWithReference, String referenceString, Map<String, Object> referencedObjects, List<ForwardReferences> forwardRefs) throws XPathExpressionException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ParseException { XPathExpression exp = xpath.compile(referenceString); Log.i("resolveRef", "xpath evaluated for :" + referenceString); Element refferredElement = (Element) exp.evaluate(elementWithReference, XPathConstants.NODE); if (refferredElement == null) { throw new ParseException("Element by reference not found"); } String xpathFromRoot = ParserUtil.getElementXpath(refferredElement); Object object = referencedObjects.get(xpathFromRoot); if (object == null) { referencedObject = objectGetter.getobjectOfClass(referencedObject.getClass(), ""); ForwardReferences forwardRef = new ForwardReferences(referencedObject, xpathFromRoot, null); forwardRefs.add(forwardRef); } else { referencedObject = object; } return referencedObject; }
public NodeList getOQasNodeList() throws SAXException, ParserConfigurationException, XPathExpressionException { NodeList result = null; if (oqUrl == null) { logger.warn("OQ.url not found. Synchronization impossible."); trace.append("Синхронизация невозможна: OQ.url не указан."); return result; } try { URLConnection oqc = oqUrl.openConnection(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(oqc.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("/root/projects/project"); result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (IOException e) { // обрабатываем только IOException - остальные выбрасываем наверх logger.error("oq project sync error: ", e); trace .append( "Синхронизация прервана из-за ошибки ввода/вывода при попытке получить и прочитать файл " + "синхронизации: ") .append(e.getMessage()) .append("\n"); } return result; }
@Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length == 0) { return; } final PsiExpression xpathArgument = arguments[0]; if (!ExpressionUtils.hasStringType(xpathArgument)) { return; } if (!PsiUtil.isConstantExpression(xpathArgument)) { return; } final PsiType type = xpathArgument.getType(); if (type == null) { return; } final String value = (String) ConstantExpressionUtil.computeCastTo(xpathArgument, type); if (value == null) { return; } if (!callTakesXPathExpression(expression)) { return; } final XPathFactory xpathFactory = XPathFactory.newInstance(); final XPath xpath = xpathFactory.newXPath(); //noinspection UnusedCatchParameter,ProhibitedExceptionCaught try { xpath.compile(value); } catch (XPathExpressionException ignore) { registerError(xpathArgument); } }
public String extractInfoObjectIdentifier(String infoObjectResponse) { String reportId = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // dbf.setNamespaceAware(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8"))); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//info-object"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; Node item = nodes.item(0); if (item != null) { NamedNodeMap attributesMap = item.getAttributes(); Node idAttribute = attributesMap.getNamedItem("id"); reportId = idAttribute.getNodeValue(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return reportId; }
private void checkBomVersionInPom(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc = null; try { builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(new StringReader(xml))); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = null; String bom_version = null; try { expr = xpath.compile("/project/properties/version.jboss.bom"); bom_version = (String) expr.evaluate(doc, XPathConstants.STRING); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertEquals( "jboss bom version in pom differs from the one given by wizard", version, bom_version); }
public NodeList запросNodes(String запрос) throws XPathExpressionException { XPathExpression выражение; выражение = xPath.compile(запрос); return (NodeList) выражение.evaluate(документ.getDocumentElement(), XPathConstants.NODESET); }
public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath) throws XPathExpressionException { List<String> list = new ArrayList<String>(); XPathFactory factory = XPathFactory.newInstance(); // 2. Use the XPathFactory to create a new XPath object XPath xpath = factory.newXPath(); xpath.setNamespaceContext(nsc); // 3. Compile an XPath string into an XPathExpression XPathExpression expression = xpath.compile(exprString); // 4. Evaluate the XPath expression on an input document Node result = (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE); String svcName = null; NamedNodeMap attMap = result.getAttributes(); Node att = attMap.getNamedItem("group"); if (att != null) svcName = att.getNodeValue(); if (result != null) { list.add(result.getNodeName()); list.add(result.getTextContent()); list.add(svcName); } factory = null; xpath = null; expression = null; result = null; attMap = null; att = null; return list; }
public Double запрос„исла(String запрос) throws XPathExpressionException { XPathExpression выражение; выражение = xPath.compile(запрос); return (Double) выражение.evaluate(документ.getDocumentElement(), XPathConstants.NUMBER); }