simplexml.py 862 B

12345678910111213141516171819202122232425262728293031323334
  1. # coding: utf-8
  2. #
  3. try:
  4. from lxml import etree
  5. LXML = True
  6. except:
  7. import xml.etree.ElementTree as ET
  8. LXML = False
  9. def safe_xmlstr(s):
  10. return s.replace("$", "-")
  11. def xpath_findall(xpath, xml_content):
  12. """
  13. Search xml by xpath
  14. Returns:
  15. List of Element [Element...]
  16. """
  17. if LXML:
  18. # print(xml_content)
  19. root = etree.fromstring(xml_content.encode('utf-8'))
  20. for node in root.xpath("//node"):
  21. node.tag = safe_xmlstr(node.attrib.pop("class"))
  22. return root.xpath(
  23. xpath, namespaces={"re": "http://exslt.org/regular-expressions"})
  24. else:
  25. root = ET.fromstring(xml_content)
  26. for node in root.findall(".//node"):
  27. node.tag = safe_xmlstr(node.attrib.pop("class"))
  28. return root.findall(xpath if xpath.startswith(".") else "." + xpath)