您的位置:宽带测速网 > 网络知识 > lxml怎么处理XML命名空间

lxml怎么处理XML命名空间

2025-06-22 12:34来源:互联网 [ ]

在lxml中处理XML命名空间,可以通过传递一个字典给namespaces参数来定义命名空间的前缀和URI,然后在使用XPath表达式时可以使用这些前缀来访问节点。

例如:

from lxml import etree# 定义命名空间的前缀和URInamespaces = {'ns': 'http://www.example.com/ns'}# 创建XML文档xml_str = """<ns:root xmlns:ns="http://www.example.com/ns"><ns:child>Child Element</ns:child></ns:root>"""root = etree.fromstring(xml_str)# 添加命名空间映射etree.register_namespace('ns', 'http://www.example.com/ns')# 使用XPath表达式来选择节点child_node = root.xpath('//ns:child', namespaces=namespaces)[0]print(child_node.text)

在上面的例子中,我们定义了一个名为ns的命名空间前缀,并将其映射到URIhttp://www.example.com/ns。然后我们使用XPath表达式//ns:child来选择<ns:child>节点,并打印其文本内容。