Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>XPath does actually include a method of doing this safely, in that it permits <a href="http://www.w3.org/TR/xpath#section-Expressions" rel="nofollow noreferrer">variable references</a> in the form <code>$varname</code> in expressions. The library on which PHP's SimpleXML is based <a href="http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterVariable" rel="nofollow noreferrer">provides an interface to supply variables</a>, however this <a href="http://php.net/manual/en/function.simplexml-element-xpath.php" rel="nofollow noreferrer">is not exposed by the xpath function</a> in your example.</p> <p>As a demonstration of really how simple this can be:</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; n = etree.fromstring('&lt;n a=\'He said "I&amp;apos;m here"\'/&gt;') &gt;&gt;&gt; n.xpath("@a=$maybeunsafe", maybeunsafe='He said "I\'m here"') True </code></pre> <p>That's using <a href="http://codespeak.net/lxml/" rel="nofollow noreferrer">lxml</a>, a python wrapper for the same underlying library as SimpleXML, with a similar <a href="http://codespeak.net/lxml/xpathxslt.html#the-xpath-method" rel="nofollow noreferrer">xpath function</a>. Booleans, numbers, and node-sets can also be passed directly.</p> <p>If switching to a more capable XPath interface is not an option, a workaround when given external string would be something (feel free to adapt to PHP) along the lines of:</p> <pre><code>def safe_xpath_string(strvar): if "'" in strvar: return "',\"'\",'".join(strvar.split("'")).join(("concat('","')")) return strvar.join("''") </code></pre> <p>The return value can be directly inserted in your expression string. As that's not actually very readable, here is how it behaves:</p> <pre><code>&gt;&gt;&gt; print safe_xpath_string("basic") 'basic' &gt;&gt;&gt; print safe_xpath_string('He said "I\'m here"') concat('He said "I',"'",'m here"') </code></pre> <p>Note, you can't use escaping in the form <code>&amp;apos;</code> outside of an XML document, nor are generic XML serialisation routines applicable. However, the XPath concat function can be used to create a string with both types of quotes in any context.</p> <p>PHP variant:</p> <pre><code>function safe_xpath_string($value) { $quote = "'"; if (FALSE === strpos($value, $quote)) return $quote.$value.$quote; else return sprintf("concat('%s')", implode("', \"'\", '", explode($quote, $value))); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload