无效的 XPath 表达式:需要令牌

我有以下 XML 有效负载:

<?xml version="1.0" encoding="UTF-8" ?><product>
  <discount class="standard">
    <id>123</id>
    <beginDate>20181205</beginDate>
    <endDate>20181225</endDate>
  </discount>
  <account>12345</account></product>

元素上的属性可以具有以下值:classdiscount

  • standard

  • special

  • custom

  • sale

我正在尝试编写一个 XPath 表达式,如果 具有这些值之一的 elemtn,则该表达式将匹配。我最好的尝试:product/discountclass

/product/discount[@class]/[@class = 'standard' or @class = 'special' or @class = 'customer' or @class = 'sale']

生成以下错误:

InvalidXPathExpression: Invalid xpath: /product/discount[@class]/[@class = 'standard' or @class = 'special' or @class = 'customer' or @class = 'sale']. Reason: javax.xml.xpath.XPathExpressionException: javax.xml.transform.TransformerException: A location step was expected following the '/' or '//' token.

任何想法,我的XPath有什么问题?


慕娘9325324
浏览 201回答 2
2回答

德玛西亚99

如错误消息所示,需要后跟一个位置步骤。因此, 不是有效的 xPath 表达式。//[@class = 'standard' ...]相反,请尝试:/product/discount[@class&nbsp;=&nbsp;'standard'&nbsp;or&nbsp;@class&nbsp;=&nbsp;'special'&nbsp;or&nbsp;@class&nbsp;=&nbsp;'customer'&nbsp;or&nbsp;@class&nbsp;=&nbsp;'sale']

RISEBY

只是为了好玩,一个比@jsheeran个更好的XPath 1.0表达式可能是:/product/discount[@class[.='standard' or .='special' or .='customer' or .='sale']]如果属性是唯一的标记,并且某些特殊字符(如 )不能是其中的一部分,则可以使用以下 XPath 1.0“item IN 序列”表达式:class&#x20;/product&nbsp; &nbsp;/discount[&nbsp; &nbsp; &nbsp; contains(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;' standard special customer sale ',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;concat(' ',@class,' ')&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp;]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java