commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Matt Benson <gudnabr...@gmail.com>
Subject Re: [jxpath] how to get map key values?
Date Tue, 29 Mar 2011 15:28:37 GMT
On Tue, Mar 29, 2011 at 10:13 AM,  <fovea1959-apache@yahoo.com> wrote:
> I am using a thirdparty library that is handing me a map. I have been using jxpath to
fish values out of nested structures in the map values.... but now I need to know the map
*key* values. I know how to get the *entries*, but the finding out the keys from jxpath eludes
me.
>
>  public void jxpathMapTest() throws Exception {
>     Map<String,String> m = new HashMap<String,String>();
>     m.put("one-key", "one-value");
>     m.put("two-key", "two-value");
>     JXPathContext jxPathContext = JXPathContext.newContext(m);
>     jxPathContext.setLenient(true);
>
>     Scanner scanner = new Scanner(System.in);
>     String s = null;
>
>     while ((s = scanner.nextLine()) != null) {
>       try {
>         System.out.println ("==============================================================");
>         System.out.println ("trying " + s);
>         for (Iterator<? extends Object> i = jxPathContext.iterate(s); i.hasNext();
) {
>           Object o = i.next();
>           if (o == null) {
>             System.out.println ("null");
>           } else {
>             System.out.println (o.getClass() + ", value '" + o + "'");
>           }
>         }
>       } catch (Exception e) {
>         System.out.println (s + " failed: " + e);
>       }
>     }
>   }
>
> Test results:
> ==============================================================
> trying /
> class java.util.HashMap, value '{two-key=two-value, one-key=one-value}'
> ==============================================================
> trying /*
> class java.lang.String, value 'one-value'
> class java.lang.String, value 'two-value'
> ==============================================================
> trying /@name
> ==============================================================
> trying /name
> ==============================================================
> trying /key
> ==============================================================
> trying /keys()
> /keys() failed: org.apache.commons.jxpath.JXPathInvalidSyntaxException: Invalid XPath:
'/keys()'. Syntax error after: '/k'
>
>

IIRC, JXPath doesn't like lists, maps, etc. at the root level.  Wrap
these in something, e.g. [lang] MutableObject or whatever container
you like, then try @name.  This is all from memory, YMMV.

Matt
Mime
View raw message