1

I have the following Java Method that uses XQuery:

 public String getLocationByName(String name) {
            final String nameToQueryFor = name;
            return engine.new Query<String>(MY_COLLECTION) {

                @Override
                protected String query(Collection collection) throws Exception {
                    XQueryService service = queryService();

                    ResourceSet resourceSet = service.query(
                            format("//Products/Product[name='%s']" +
                                            "/attribute"
                                    , StringEscapeUtils.escapeXml(nameToQueryFor)
                            ));

                    List<String> results = newArrayList();

                    for (String resource : new IterableStringResources(resourceSet)) {
                        results.add(resource);
                    }
                    return results.get(0);
                }
            }.execute();
        }

As can be seen I currently am only querying using one parameter, i.e. name.

I am a beginner with XQuery, How can I alter this Xquery to take an additional parameter: price

My method would now become:

 public String getLocationByNameAndPrice(String name)
1
  • Also note that it might be safer and easier to use exist-db.org/api/org/exist/xmldb/… to set up variables for your Query so that you can then use //Products/Product[name=$name] instead of string formatting and concatenation. Commented Oct 17, 2016 at 11:30

1 Answer 1

1

Just include the condition into your XPath, e.g.:

format("//Products/Product[name='%s' and price='%s']/attribute",
  StringEscapeUtils.escapeXml(nameToQueryFor),
  StringEscapeUtils.escapeXml(priceToQueryFor))

The exact syntax of the query of course depends on your XML document.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.