lxml怎么处理XML命名空间
在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>
节点,并打印其文本内容。