5

我收到以下代码的无效 Xpath 异常。

current.Name = current.Name.replace("'", "\'");
System.out.println(current.Name );
String xp1 = "//page[@name='"+current.Name+"']" ;
Element n = (Element) oDocument.selectSingleNode(xp1+"/Body/contents");

当 current.name 中的字符串中包含撇号时发生异常

current.name: "活动分区重新分区"

错误信息

4

2 回答 2

2

你可以通过加倍来逃避引用:

current.Name = current.Name.replace("'", "''");

编辑:

对于 Xpath 1.0,您可以尝试以下操作:

String xp1 = "//page[@name=\""+current.Name+"\"]" ;

即使用双引号而不是单引号来分隔名称(尽管这意味着您将无法搜索带有双引号的字符串。

另请注意,对于第二种解决方案,您不需要替换引号。

于 2013-11-08T12:45:02.227 回答
1

在 XPath 表达式中,字符串可以用单引号或双引号分隔。您可以在双引号字符串中包含单引号字符或在单引号字符串中包含双引号字符,但反之亦然 - 在 XPath 1.0 中没有转义机制,因此不可能在同一字符串文字中同时包含单引号和双引号字符,您必须使用类似的技巧

concat('Strings can use "double" quotes', " or 'single' quotes")

通常,您应该避免使用字符串连接构造 XPath 表达式,而是使用引用变量的常量 XPath 表达式,并使用 XPath 库提供的机制传入变量值。这类似于使用PreparedStatement带有参数占位符的 JDBC,而不是连接 SQL 字符串。您的评论表明您正在使用 dom4j,在该库中注入变量值的机制是:

import org.jaxen.SimpleVariableContext;
import org.dom4j.XPath;

XPath xpath = oDocument.createXPath("//page[@name=$targetName]/Body/contents");
SimpleVariableContext ctx = new SimpleVariableContext();
xpath.setVariableContext(ctx);
ctx.setVariableValue("targetName", current.Name);
Element n = (Element)xpath.selectSingleNode(oDocument);

VariableContext您可以对许多不同的XPath对象重复使用相同的内容。因为它不current.Name通过 XPath 解析器传递值,所以这种方法在所有情况下都可以正常工作,即使值包含两种类型的引号字符。

于 2013-11-08T13:20:33.250 回答