I have a XML document that has namespaces in it.  I want to use the find* 
methods to select elements but it's looks like it is not possible without 
specifying namespaces explicitly to every call.  Is this true?  Is this by 
design?  This seems very burdensome to do so when namespaces are included in 
the XML document.  It would be really nice if the namespaces in the XML 
document could be considered.
xml = b"""<?xml version="1.0" encoding="UTF-8"?><root 
xmlns="urn:defaultnamespace">    
<Timestamp>2025-01-09T17:46:08.766Z</Timestamp>    <namespaced 
xmlns:ns="urn:subns">        <rootdefault>text</rootdefault>        
<ns:element>element</ns:element>    </namespaced></root>"""from lxml import 
etreexml_doc = etree.fromstring(xml)print(xml_doc)print("namespaces: " + 
str(xml_doc.nsmap))print(f"find root without namespace 
{xml_doc.find(".")}")print(f"find root with namespace {xml_doc.find(".", 
namespaces = {**xml_doc.nsmap})}")print(f"find Timestamp without namespace 
{xml_doc.find("./Timestamp")}")print(f"find Timestamp with namespace 
{xml_doc.find("./Timestamp", namespaces = {**xml_doc.nsmap})}")print(f"find 
namespaced without namespace {xml_doc.find("./namespaced")}")print(f"find 
namespaced with namespace {xml_doc.find("./namespaced", namespaces = 
{**xml_doc.nsmap})}")print(f"find element with namespace 
{xml_doc.find("./namespaced/rootdefault")}")print(f"find rootdefault with 
namespace {xml_doc.find("./namespaced/rootdefault", namespaces = 
{**xml_doc.nsmap})}")print(f"find namespaced no namespace 
{xml_doc.find("./namespaced/element")}")try:    print(f"find namespaced default 
namespace only {xml_doc.find("./namespaced/ns:element", namespaces = {None: 
"urn:defaultnamespace"})}")except SyntaxError as e:    print(f"find namespaced 
default namespace only error {e}")print(f"find namespaced ns namespace only 
{xml_doc.find("./namespaced/ns:element", namespaces = {"ns": 
"urn:subns"})}")print(f"find namespaced with full namespace 
{xml_doc.find("./namespaced/ns:element", namespaces = {None: 
"urn:defaultnamespace", "ns": "urn:subns"})}")
_______________________________________________
lxml - The Python XML Toolkit mailing list -- lxml@python.org
To unsubscribe send an email to lxml-le...@python.org
https://mail.python.org/mailman3/lists/lxml.python.org/
Member address: arch...@mail-archive.com

Reply via email to