{ System.setProperty( XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI, "net.sf.saxon.xpath.XPathFactoryImpl"); xPath = XPathFactory.newInstance().newXPath(); System.err.println("SaxonXPathParser: xpath: " + XPathFactory.newInstance().getClass()); }
protected Object exec(Object[] args, Context context) { try { int nargs = args.length; if (nargs == 2) { Object target = args[0]; String expr = (String) args[1]; XPath xpath = XPathFactory.newInstance().newXPath(); if (target instanceof Node) { return xpath.evaluate(expr, target, XPathConstants.NODESET); } else { return xpath.evaluate(expr, Util.inputSource(target, context), XPathConstants.NODESET); } } else if (nargs == 3) { Object target = args[0]; String expr = (String) args[1]; XPath xpath = XPathFactory.newInstance().newXPath(); if (target instanceof Node) { return xpath.evaluate(expr, target, XPathConstants.NODESET); } else { return xpath.evaluate(expr, Util.inputSource(target, context), XPathConstants.NODESET); } } else { undefined(args, context); return null; } } catch (Exception e) { throw new PnutsException(e, context); } }
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; }
/* goodG2B() - use goodsource and badsink */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b()) .goodG2B_source(request, response); final String xmldoc = "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml"; /* assume username||password as source */ String[] tokens = data.split("||"); if (tokens.length < 2) { return; } String uname = tokens[0]; String pword = tokens[1]; /* build xpath */ XPath xp = XPathFactory.newInstance().newXPath(); InputSource inxml = new InputSource(xmldoc); /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize * The user input should be canonicalized before validation. */ /* FLAW: user input is used without validate */ String query = "//users/user[name/text()='" + uname + "' and pass/text()='" + pword + "']" + "/secret/text()"; String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING); }
@Test public void testFieldHasMatchingUserValues() throws Exception { LOG.info("testFieldHasMatchingUserValues"); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); Document doc = db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML)); // enumerate all fields final String fieldDefs = "/edlContent/edl/field/display/values"; NodeList nodes = (NodeList) xpath.evaluate(fieldDefs, doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String name = (String) xpath.evaluate("../../@name", node, XPathConstants.STRING); LOG.debug("Name: " + name); LOG.debug("Value: " + node.getFirstChild().getNodeValue()); final String expr = "/edlContent/data/version[@current='true']/fieldEntry[@name=current()/../../@name and value=current()]"; NodeList matchingUserValues = (NodeList) xpath.evaluate(expr, node, XPathConstants.NODESET); LOG.debug(matchingUserValues + ""); LOG.debug(matchingUserValues.getLength() + ""); if ("gender".equals(name)) { assertTrue("Matching values > 0", matchingUserValues.getLength() > 0); } for (int j = 0; j < matchingUserValues.getLength(); j++) { LOG.debug(matchingUserValues.item(j).getFirstChild().getNodeValue()); } } }
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); } }
/** * 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; }
private void initXpath() { factory = XPathFactory.newInstance(); namespaceContext = new NamespaceContextImpl(); namespaceContext.startPrefixMapping("saml1", "urn:oasis:names:tc:SAML:1.0:assertion"); xpath = factory.newXPath(); xpath.setNamespaceContext(namespaceContext); }
public GetAuthDetailsResponseDetailsType(Node node) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node childNode = null; NodeList nodeList = null; childNode = (Node) xpath.evaluate("FirstName", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.FirstName = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("LastName", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.LastName = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("Email", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.Email = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("PayerID", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.PayerID = childNode.getTextContent(); } }
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; }
private String getAttribute(Document document, String attribute) throws XPathExpressionException { return (String) XPathFactory.newInstance() .newXPath() .compile("/Context/Resource/" + attribute) .evaluate(document.getDocumentElement(), XPathConstants.STRING); }
/** * Extract an XML element. * * @param xpathExp * @param file * @return */ private Document getDocFragment(String xpathExp, XmlMetadata file) { Document testDoc = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); Node node = (Node) xpath.evaluate(xpathExp, file.getParsedDocument(), XPathConstants.NODE); if (node != null) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(buffer)); String testStr = buffer.toString(); LOG.debug("src string: " + testStr); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); testDoc = dBuilder.parse(new InputSource(new ByteArrayInputStream(testStr.getBytes("utf-8")))); } } catch (XPathExpressionException xee) { LOG.error("Invalid XPath expression: " + xpathExp); } catch (Exception e) { LOG.error("Error extracting XML content: ", e); } return testDoc; }
@Override public String summaryAsJson() { int archetypes = 0; try { String xml = archetypeCatalogAsXml(); Document dom = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(xml.getBytes())); Object val = XPathFactory.newInstance() .newXPath() .evaluate( "count(/archetype-catalog/archetypes/archetype)", dom, XPathConstants.NUMBER); double num = (double) val; archetypes = (int) num; } catch (Exception e) { // ignore } StringBuilder sb = new StringBuilder(); sb.append("{\n"); sb.append(" \"version\": \"" + getCatalogVersion() + "\",\n"); sb.append(" \"eips\": " + findModelNames().size() + ",\n"); sb.append(" \"components\": " + findComponentNames().size() + ",\n"); sb.append(" \"dataformats\": " + findDataFormatNames().size() + ",\n"); sb.append(" \"languages\": " + findLanguageNames().size() + ",\n"); sb.append(" \"archetypes\": " + archetypes + "\n"); sb.append("}"); return sb.toString(); }
public XformParserODK() { XPathFactory xPathFactory = XPathFactory.newInstance(); this.xPath = xPathFactory.newXPath(); SimpleNamespaceContext namespaces = new SimpleNamespaceContext(); namespaces.setBindings(NAMESPACE_MAP); this.xPath.setNamespaceContext(namespaces); }
/** * This method evaluates the xpath expression on the supplied node. The result can either be a * document fragment, a text node value or null if the expression references a missing part of the * document. * * @param xpath The xpath expression * @param node The node * @return The result, or null if not found (which may be due to an expression error) */ public static String evaluate(String xpath, Object node) { Node domNode = getNode(node); if (domNode == null) { log.severe("Unable to evaluate non DOM Node object"); return null; } // If no xpath expression, then serialize if (xpath == null || xpath.trim().length() == 0) { return serialize(node); } // TODO: HWKBTM-104 Investigate caching compiled xpath expressions try { xpath = getExpression(xpath); XPath xp = XPathFactory.newInstance().newXPath(); Node result = (Node) xp.evaluate(xpath, domNode, XPathConstants.NODE); if (result != null) { if (result.getNodeType() == Node.TEXT_NODE) { return result.getNodeValue(); } else if (result.getNodeType() == Node.ATTRIBUTE_NODE) { return result.getNodeValue(); } return serialize(result); } } catch (Exception e) { log.log(Level.SEVERE, "Failed to evaluate xpath '" + xpath + "'", e); } return null; }
/** * This method evaluates the predicate based on the xpath expression on the supplied node. * * @param xpath The xpath expression * @param node The node * @return The result */ public static boolean predicate(String xpath, Object node) { Node domNode = getNode(node); if (domNode == null) { log.severe("Unable to evaluate non DOM Node object"); return false; } if (xpath == null) { log.severe("Predicate has not xpath expression"); return false; } // TODO: HWKBTM-104 Investigate caching compiled xpath expressions try { xpath = getExpression(xpath); XPath xp = XPathFactory.newInstance().newXPath(); Boolean result = (Boolean) xp.evaluate(xpath, domNode, XPathConstants.BOOLEAN); if (result != null) { return result; } } catch (Exception e) { log.log(Level.SEVERE, "Failed to execute predicate xpath '" + xpath + "'", e); } return false; }
/** * Class has a static method to load a key from a KDBX XML Key File * * @author jo */ public class KdbxKeyFile { static XPath xpath = XPathFactory.newInstance().newXPath(); /** * Load a key from an InputStream with a KDBX XML key file. * * @param inputStream the input stream holding the key * @return they key or null if there was a problem */ public static byte[] load(InputStream inputStream) { String base64; try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = documentBuilder.parse(inputStream); base64 = (String) xpath.evaluate("//KeyFile/Key/Data/text()", doc, XPathConstants.STRING); if (base64 == null) { return null; } } catch (Exception e) { return null; } // android compatibility return Base64.decodeBase64(base64.getBytes()); } }
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; }
/** * Runs an XPath expression on this node. * * @param env * @param expression * @return array of results * @throws XPathExpressionException */ public Value xpath(Env env, String expression) { try { XPath xpath = XPathFactory.newInstance().newXPath(); InputSource is = new InputSource(asXML(env).toInputStream()); NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET); int nodeLength = nodes.getLength(); if (nodeLength == 0) return NullValue.NULL; // There are matching nodes ArrayValue result = new ArrayValueImpl(); for (int i = 0; i < nodeLength; i++) { Node node = nodes.item(i); boolean isPrefix = node.getPrefix() != null; SimpleXMLElement xml = buildNode(env, _cls, null, nodes.item(i), node.getNamespaceURI(), isPrefix); result.put(wrapJava(env, _cls, xml)); } return result; } catch (XPathExpressionException e) { env.warning(e); log.log(Level.FINE, e.getMessage()); return NullValue.NULL; } }
public MergePoint(MergeHandler handler, Document doc1, Document doc2) { this.handler = handler; this.doc1 = doc1; this.doc2 = doc2; XPathFactory factory = XPathFactory.newInstance(); xPath = factory.newXPath(); }
/** * Parses a single <code><result></code> entry from the Google Places XML response. * * @param resultNode * @return * @throws XPathExpressionException */ private GooglePlace parseSingleResult(Node resultNode) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); String expr; GooglePlace place = new GooglePlace(); if (resultNode != null) { expr = "name"; place.setName((String) xpath.evaluate(expr, resultNode, XPathConstants.STRING)); expr = "formatted_address"; place.setFormattedAddress((String) xpath.evaluate(expr, resultNode, XPathConstants.STRING)); expr = "geometry/location/lat"; String lat = (String) xpath.evaluate(expr, resultNode, XPathConstants.STRING); if (lat != null && lat.length() > 0) { place.setLatitude(Double.parseDouble(lat)); } expr = "geometry/location/lng"; String lng = (String) xpath.evaluate(expr, resultNode, XPathConstants.STRING); if (lng != null && lng.length() > 0) { place.setLongitude(Double.parseDouble(lng)); } } return place; }
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 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()); } } } }
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; }
/** * 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); } }
/* goodB2G() - use badsource and goodsink */ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (new CWE643_Unsafe_Treatment_of_XPath_Input__getCookiesServlet_61b()) .goodB2G_source(request, response); final String xmldoc = "\\src\\testcases\\CWE643_Unsafe_Treatment_of_XPath_Input\\console_to_evaluate\\CWE643_Unsafe_Treatment_of_XPath_Input__helper.xml"; /* assume username||password as source */ String[] tokens = data.split("||"); if (tokens.length < 2) { return; } /* FIX: validate input using StringEscapeUtils */ String uname = StringEscapeUtils.escapeXml(tokens[0]); String pword = StringEscapeUtils.escapeXml(tokens[1]); /* build xpath */ XPath xp = XPathFactory.newInstance().newXPath(); InputSource inxml = new InputSource(xmldoc); String query = "//users/user[name/text()='" + uname + "' and pass/text()='" + pword + "']" + "/secret/text()"; String secret = (String) xp.evaluate(query, inxml, XPathConstants.STRING); }
@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 OptionSelectionDetailsType(Node node) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node childNode = null; NodeList nodeList = null; childNode = (Node) xpath.evaluate("OptionSelection", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.optionSelection = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("Price", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.price = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("OptionType", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.optionType = OptionTypeListType.fromValue(childNode.getTextContent()); } nodeList = (NodeList) xpath.evaluate("PaymentPeriod", node, XPathConstants.NODESET); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node subNode = nodeList.item(i); this.paymentPeriod.add(new InstallmentDetailsType(subNode)); } } }
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(); } }