#!/usr/bin/env python # -*- coding: utf-8 mode: python -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8 u"""%(scriptname)s: Faire une requête xpath USAGE %(scriptname)s -f input expr OPTIONS -f, --input INPUT Spécifier un fichier en entrée""" import i_need_py25 import os, sys, mimetypes, types from os import path from xml.dom import minidom from ulib.all import * from ulib.ext import xpath def display_help(): uprint(__doc__ % globals()) def dumprs(rs): tr = type(rs) if tr is types.BooleanType: print rs and "true" or "false" elif tr is types.FloatType: print rs elif tr is types.UnicodeType: print rs.encode("utf-8") elif tr is types.ListType: for r in rs: dumprs(r) elif isinstance(rs, minidom.Element): print rs.toxml("utf-8") elif isinstance(rs, minidom.Attr): print rs.value.encode("utf-8") elif isinstance(rs, minidom.Text): print rs.data.encode("utf-8") else: die("type non géré: %s (%s)" % (str(rs), tr)) def run_xpath(): options, longoptions = build_options([ ('h', 'help', "Afficher l'aide"), ('f:', 'input=', "Spécifier un fichier en entrée"), ]) options, args = get_args(None, options, longoptions) file = None for option, value in options: if option in ('-h', '--help'): display_help() sys.exit(0) elif option in ('-f', '--input'): file = value if len(args) == 0: die("Vous devez spécifier l'expression XPATH") if file is None or file == "-": inf = sys.stdin close = False else: inf = open(file, 'rb') close = True dom = minidom.parse(inf) if close: inf.close() for expr in args: dumprs(xpath.find(expr, dom)) if __name__ == '__main__': run_xpath()