简体   繁体   中英

Valid XPath expression

Just two questions:

  1. How can I check if the string assigned to a variable corresponds to a valid XPath expression?
  2. How can I return a customized error message in case the requested resource does not exist?
  1. If the XPath is invalid, you'll get an exception.
  2. If the requested node does not exist, you'll get an empty result set.

For example:

from lxml import etree
from StringIO import StringIO
tree = etree.parse(StringIO('<foo><bar></bar></foo>'))
try:
  tree.xpath('\BAD XPATH')
  print '1. Valid XPath'
except etree.XPathEvalError, e:
  print '1. Invalid XPath: ', e
if not tree.xpath('/foo/xxx'):
  print '2. Requested node does not exist.'

Runs as follows:

1. Invalid XPath:  Invalid expression
2. Requested node does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM