Search code examples
javaxmlxqueryxquery-sqlexist-db

How to query XML inside a tag?


I am trying to query the value for location with the attribute tag in my xml below. How can I do so?

My current query only returns the value for the full attribute tag but I only want the value for location, which in this case is "sampleLocation"?

i.e: location="sampleLocation"

XML:

<Products>
    <Product>
        <name>Sample name</name>
        <attribute id="sampleid" location="sampleLocation" type="sampleType"/>
    </product>
</Products> 

Current code:

  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();
    }

Solution

  • I was able to solve this using the following query:

    "//Products/Product[name='%s']/attribute/@Location/string()"
    

    which returns: "sampleLocation"

    Note: without using the /string() at the end it was giving the error:

    attribute 'Location' has no parent element