"""xpath functions, some should go to surks""" #import copy #import os import sys from lxml import etree #xsimport docing from nitpo import Nitpo class Xpaths(Nitpo): def __init__(self, do_verbose=False): super().__init__() ns = self.const['ns'] self.N = {'n': self.const['ns']} self.nsmap = {None: ns} self.do_verbose = do_verbose def has_it(self, doc, xp): count = len(doc.xpath(xp, namespaces=self.const['nsmap'])) if count == 0: return True return False def txt(self, doc): string = etree.tostring(doc, prettyprint=True).decode() return string def zero_or_one(self, doc, xp): outs = doc.xpath(xp, namespaces=self.const['nsmap']) if len(outs) == 0: return None if len(outs) == 1: return outs[0] err = self.txt(doc) + ' must not have several ' + xp if self.is_dev(): raise Exception(err) print(err, file=sys.stderr) # def live_surk(self, doc, repcode): # live_xp = '/n:profile/n:live/n:surk[@repcode="' + repcode + '"]' # return self.zero_or_one(doc, live_xp) # # def live_surks(self, doc): # xp = '/n:profile/n:live/n:surk' # outs = doc.xpath(xp, namespaces=self.N) # return outs # # def get_emad(self, ele): # xp = '@emad' # emads = ele.xpath(xp, namespaces=self.const['nsmap']) # if len(emads) > 0: # return emads[0] # print_ele = etree.tostring(ele, pretty_print=True).decode() # print_err = "xpaths: no emad in \n" + print_ele # print(print_err, file=sys.stderr) # return None # # def get_spro(self, ele, repcode=None): # xp = "//n:surk[@repcode='" + repcode + "']/@spro" # spros = ele.xpath(xp, namespaces=self.const['nsmap']) # if len(spros) > 0: # return spros[0] # if len(spros) == 0: # # omnibus case # xp = '//n:surk/@spro' # spros = ele.xpath(xp, namespaces={'n': self.const['ns']}) # if len(spros) > 0: # return spros[0] # print_ele = etree.tostring(ele, pretty_print=True).decode() # print_err = f"xpath: no spro by '{xp}' in \n" + print_ele # print(print_err, file=sys.stderr) # # return the default # return 'v' # # # # the function called by repis # # # why does this not use kapro? # def get_sint(self, ele, repcode=None): # xp = "//n:surk[@repcode='" + repcode + "']/@sint" # sints = ele.xpath(xp, namespaces=self.const['nsmap']) # if len(sints) > 0: # return sints[0] # if len(sints) == 0: # # should take account of the spro # xp = "//n:surk[@repcode='" + repcode + "']/@spro" # spros = ele.xpath(xp, namespaces=self.const['nsmap']) # if len(spros) == 1 and spros[0] == 'a': # return 'd' # # almost all data have the spro # # omnibus case, rare # xp = '//n:omnibus/n:surk/@emad' # omnis = ele.xpath(xp, namespaces=self.const['nsmap']) # if len(omnis) > 0: # return 'a' # print_ele = etree.tostring(ele, pretty_print=True).decode() # print_err = f"xpath: no spro by '{xp}' in \n" + print_ele # print(print_err, file=sys.stderr) # # return the default # return 's'