【问题标题】:Invalid XPath expression exception due to presence of apostrophe in name由于名称中存在撇号,XPath 表达式异常无效
【发布时间】:2013-11-20 11:28:24
【问题描述】:

我收到以下代码的无效 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: "Répartition par secteur d'activité"

错误信息

【问题讨论】:

  • 错误消息“org.dom4j.InvalidXPathException: Invalid XPath expression: //page[@name='Répartition par secteur d''activité']/pageBody/contents Expected: ]"

标签: java xml xpath


【解决方案1】:

你可以通过加倍来转义引用:

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

编辑:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    这样的技巧
    concat('Strings can use "double" quotes', " or 'single' quotes")
    

    通常,您应该避免使用字符串连接构造 XPath 表达式,而是使用引用变量的常量 XPath 表达式,并使用 XPath 库提供的机制传递变量值。这类似于使用带有参数占位符的 JDBC PreparedStatement 而不是连接 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 对象重复使用。由于它不会通过 XPath 解析器传递 current.Name 值,因此这种方法在所有情况下都可以正常工作,即使该值包含两种类型的引号字符。

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2017-10-12
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多