如何查询标签内的XML?

时间:2016-10-13 10:50:36

标签: java xml xquery xquery-sql exist-db

我正在尝试使用下面的xml中的属性标记查询位置值。我怎么能这样做?

我当前的查询只返回完整属性标记的值,但我只想要location的值,在这种情况下是“sampleLocation”?

即:location="sampleLocation"

XML:

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

当前代码:

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

3 个答案:

答案 0 :(得分:0)

[编辑&#39;位置&#39; +更正]

"//Products/Product/name[text()=%s]/next-sibling::attribute/a‌​ttribute::location"

翻译:在//Products/Product的上下文中,选择具有给定文本的元素<name>。然后使用<attribute>类型的下一个兄弟元素,从中获取location属性(此元素的属性)的值

&x; xpath位置路径的一些示例&#39; straight from the horse's mouth

答案 1 :(得分:0)

我的建议是

//Product[child::name/text()={$nameToQueryFor}]/attribute/@location

仅当变量绑定到元素类型

的值时才会起作用

答案 2 :(得分:0)

我能够使用以下查询解决此问题:

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

返回:“sampleLocation”

注意:最后没有使用/string(),它给出了错误:

attribute 'Location' has no parent element