add support for namespace declarations on non-root elements
2 files changed, 13 insertions(+), 7 deletions(-)

M ChangeLog.md
M xgrep.py
M ChangeLog.md +6 -1
@@ 1,3 1,8 @@ 
+2024-02-01:
+
+* add support for namespace declarations on non-root elements
+* bump version to 2.12
+
 2023-11-04:
 
 * reformat code

          
@@ 65,7 70,7 @@ 2019-04-13:
 
 2019-04-12:
 
-* support for namespaces
+* add support for namespaces
 * bump version to 2.0
 
 2018-11-19:

          
M xgrep.py +7 -6
@@ 1,6 1,6 @@ 
 #!/usr/bin/python3
 # xgrep.py -- search for elements in XML files, using XPath 1.0 expressions
-# Andreas Nolda 2023-11-04
+# Andreas Nolda 2024-02-01
 
 import sys
 import argparse

          
@@ 11,7 11,7 @@ from blessings import Terminal
 from lxml import etree
 
 
-version = "2.11"
+version = "2.12"
 
 
 parser = argparse.ArgumentParser()

          
@@ 60,7 60,7 @@ term = Terminal(force_styling=args.force
 
 
 def insert_default_ns(expr, nsmap):
-    if nsmap:
+    if "default" in nsmap:
         subexprs = re.split(r"("
                             r"/|"                                                  # /
                             r"[a-z-]+::|"                                          # axis::

          
@@ 210,9 210,10 @@ def main():
             tree = etree.parse(file, xml_parser)
             root = tree.getroot()
             # cf. https://stackoverflow.com/q/4210730:
-            nsmap = {key if key is not None
-                         else "default": value
-                     for key, value in root.nsmap.items()}
+            nsmaps = [element.nsmap for element in root.iter()]
+            nsmap = {key if key is not None else "default": value
+                     for nsmap in nsmaps for key, value in nsmap.items()}
+
             nsexpr = insert_default_ns(args.expr, nsmap)
             # add regexp namespace *after* inserting default namespace
             if args.regex: