在lxml中處理XML命名空間的默認(rèn)值可以通過(guò)使用xpath()
方法和register_namespace()
方法來(lái)實(shí)現(xiàn)。
首先,使用register_namespace()
方法來(lái)為命名空間設(shè)置一個(gè)前綴,例如:
from lxml import etree
# 注冊(cè)命名空間前綴
etree.register_namespace('ns', 'http://www.example.com/namespace')
然后,使用xpath()
方法來(lái)查詢具有默認(rèn)命名空間的元素,例如:
# 創(chuàng)建XML文檔
xml = '''
<ns:root xmlns:ns="http://www.example.com/namespace">
<ns:child>Some content</ns:child>
</ns:root>
'''
# 解析XML文檔
root = etree.fromstring(xml)
# 使用xpath()方法查詢具有默認(rèn)命名空間的元素
elements = root.xpath('//ns:child', namespaces={'ns': 'http://www.example.com/namespace'})
# 輸出查詢結(jié)果
for element in elements:
print(element.text)
通過(guò)注冊(cè)命名空間前綴和使用xpath()
方法,可以方便地處理XML命名空間的默認(rèn)值。