从Java发送XPath变量 [英] Sending XPath a variable from Java

查看:163
本文介绍了从Java发送XPath变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XPath表达式,用于搜索静态值。在此示例中,test是该值:

I have an XPath expression that searches for a static value. In this example, "test" is that value:

XPathExpression expr = xpath.compile("//doc[contains(., 'test')]/*/text()");

如何传递变量而不是固定字符串?我在Eclipse中使用Java。有没有办法使用Java String 的值来声明XPath变量?

How can I pass a variable instead of a fixed string? I use Java with Eclipse. Is there a way to use the value of a Java String to declare an XPath variable?

推荐答案

您可以定义变量解析器并对表达式求解变量进行求值,例如 $ myvar ,例如:

You can define a variable resolver and have the evaluation of the expression resolve variables such as $myvar, for example:

XPathExpression expr = xpath.compile(// doc [contains(。,$ myVar)] / * / text());

有一个相当不错的解释这里。我之前没有真正做到这一点,所以我可能会有一个更好的例子。

There's a fairly good explanation here. I haven't actually done this before myself, so I might have a go and provide a more complete example.

更新:

考虑到这一点,可以采取一种享受。对于一个非常简单的实现的示例,您可以定义一个类,该类从地图返回给定变量的值,如下所示:

Given this a go, works a treat. For an example of a very simple implementation, you could define a class that returns the value for a given variable from a map, like this:

class MapVariableResolver implements XPathVariableResolver {
  // local store of variable name -> variable value mappings
  Map<String, String> variableMappings = new HashMap<String, String>();

  // a way of setting new variable mappings 
  public void setVariable(String key, String value)  {
    variableMappings.put(key, value);
  }

  // override this method in XPathVariableResolver to 
  // be used during evaluation of the XPath expression      
  @Override
  public Object resolveVariable(QName varName) {
    // if using namespaces, there's more to do here
    String key = varName.getLocalPart();
    return variableMappings.get(key);
  }
}

现在,声明并初始化此解析器的实例该程序,例如

Now, declare and initialise an instance of this resolver in the program, for example

MapVariableResolver vr = new MapVariableResolver() ;
vr.setVariable("myVar", "text");
...
XPath xpath = factory.newXPath();
xpath.setXPathVariableResolver(vr);

然后,在评估XPath表达式时 XPathExpression expr = xpath.compile( // doc [contains(。,$ myVar)] / * / text()); ,变量 $ myVar 将被替换使用字符串 text

Then, during evaluation of the XPath expression XPathExpression expr = xpath.compile("//doc[contains(., $myVar)]/*/text()");, the variable $myVar will be replaced with the string text.

不错的问题,我自学了一些有用的东西!

Nice question, I learnt something useful myself!

这篇关于从Java发送XPath变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆