code_junkie

Cleaning/sanitizing xpath attributes

Nov 11th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. <?php
  2. function xPathQuery($attr) {
  3. $xml = simplexml_load_file('example.xml');
  4. return $xml->xpath("//myElement[@content='{$attr}']");
  5. }
  6.  
  7. xPathQuery('This should work fine');
  8. # //myElement[@content='This should work fine']
  9.  
  10. xPathQuery('As should "this"');
  11. # //myElement[@content='As should "this"']
  12.  
  13. xPathQuery('This'll cause problems');
  14. # //myElement[@content='This'll cause problems']
  15.  
  16. xPathQuery('']/../privateElement[@content='private data');
  17. # //myElement[@content='']/../privateElement[@content='private data']
  18.  
  19. >>> from lxml import etree
  20. >>> n = etree.fromstring('<n a='He said "I&apos;m here"'/>')
  21. >>> n.xpath("@a=$maybeunsafe", maybeunsafe='He said "I'm here"')
  22. True
  23.  
  24. def safe_xpath_string(strvar):
  25. if "'" in strvar:
  26. return "',"'",'".join(strvar.split("'")).join(("concat('","')"))
  27. return strvar.join("''")
  28.  
  29. >>> print safe_xpath_string("basic")
  30. 'basic'
  31. >>> print safe_xpath_string('He said "I'm here"')
  32. concat('He said "I',"'",'m here"')
  33.  
  34. function xPathQuery($attr) {
  35. $xml = simplexml_load_file('example.xml');
  36. $to_encode = array('&', '"');
  37. $to_replace = array('&','"');
  38. $attr = replace($to_encode, $to_replace, $attr);
  39. return $xml->xpath("//myElement[@content="{$attr}"]");
  40. }
Add Comment
Please, Sign In to add comment