博客
关于我
命名空间
阅读量:502 次
发布时间:2019-03-07

本文共 3739 字,大约阅读时间需要 12 分钟。

ElementTree API在设计时,尽量避免使用前缀,而是通过命名空间(URI)来管理标签的命名空间。这种做法有助于在处理不同文档时,确保代码的清晰性和准确性。

创建带前缀和命名空间的XML树

当使用命名空间http://www.w3.org/1999/xhtml时,ElementTree会自动创建前缀html,并将其与命名空间关联。若提供的URL不正确,ElementTree会自动生成默认的前缀ns0,这样可以避免命名空间解析时的错误。

from lxml import etree# 使用命名空间时,ElementTree会自动处理前缀html_element = etree.Element("{http: www.w3.org 1999 xhtml}html")body = etree.SubElement(html_element, "{http: xhtml}body")body.text = "Hello World"print(etree.tostring(html_element, pretty_print=True))

输出结果如下:

Hello World

ElementTree的命名空间管理

ElementTree最初由James Clark提出,其主要优势在于能够无缝处理不同文档中的命名空间,无论文档是否定义了前缀。这种机制使得代码更加清晰和可靠。

命名空间的使用与管理

在实际应用中,命名空间的定义可能会变得非常长。为了避免代码冗长,通常会将命名空间存储在全局变量中。

from lxml import etreeXHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"XHTML = "{%s}" % XHTML_NAMESPACENSMAP = {'prefix_test': XHTML_NAMESPACE}# 创建带命名空间的元素html_element = etree.Element(XHTML + "html", nsmap=NSMAP)body = etree.SubElement(html_element, XHTML + "body")body.text = "Hello World"print(etree.tostring(html_element, pretty_print=True))

输出结果如下:

Hello World

QName助手类的使用

QName助手类可以帮助开发者生成或拆分限定标签名称。它支持两种主要操作方式:

from lxml import etree# 生成限定标签名称tag = etree.QName('http://www.w3.org/1999/xhtml', 'html')print(tag.localname)  # 输出: htmlprint(tag.namespace)  # 输出: http://www.w3.org/1999/xhtml# 生成带命名空间的标签名称tag = etree.QName('{http://www.w3.org/1999/xhtml}html')print(tag.localname)  # 输出: htmlprint(tag.namespace)  # 输出: http://www.w3.org/1999/xhtml# 创建带命名空间的元素root = etree.Element('{http://www.w3.org/1999/xhtml}html')tag = etree.QName(root)print(tag.localname)  # 输出: html# 生成子元素的限定标签名称tag = etree.QName(root, 'script')print(tag.text)  # 输出: {http://www.w3.org/1999/xhtml}scripttag = etree.QName('{http://www.w3.org/1999/xhtml}html', 'script')print(tag.text)  # 输出: {http://www.w3.org/1999/xhtml}script

命名空间映射的应用

ElementTree允许通过nsmap属性来管理命名空间。这个属性不仅支持元素本身定义的命名空间,还包括上下文中已知的所有前缀。

from lxml import etreeroot = etree.Element('root', nsmap={    'a': 'http://a.b/c'})child = etree.SubElement(root, 'child', nsmap={    'b': 'http://b.c/d'})print(root.nsmap)  # 输出: {'a': 'http://a.b/c'}print(child.nsmap)  # 输出: {'b': 'http://b.c/d'}# 修改映射不会影响元素本身child.nsmap['b'] = 'test'print(child.nsmap['b'])  # 输出: 'http://b.c/d'

属性中的命名空间

属性中的命名空间在ElementTree中遵循XML名称空间规范。从2.3版开始,ElementTree确保属性使用带前缀的命名空间声明。这是因为未固定属性名在名称空间中没有意义,可能会在序列化和解析过程中丢失。

from lxml import etreeXHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"XHTML = "{%s}" % XHTML_NAMESPACENSMAP = {'prefix_test': XHTML_NAMESPACE}html_element = etree.Element(XHTML + "html", nsmap=NSMAP)body = etree.SubElement(html_element, XHTML + "body")body.text = "Hello World"body.set(XHTML + "bgcolor", "#CCFFAA")print(etree.tostring(html_element, pretty_print=True))# 获取属性值print(body.get("bgcolor"))  # 输出: Noneprint(body.get(XHTML + "bgcolor"))  # 输出: #CCFFAA# 使用XPath查找带命名空间的元素find_xhtml_body = etree.ETXPath("//{%s}body" % XHTML_NAMESPACE)results = find_xhtml_body(html_element)print(results[0].tag)  # 输出: {http://www.w3.org/1999/xhtml}body# 使用通配符查找所有元素for el in html_element.iter('*'):    print(el.tag)  # 输出: {http://www.w3.org/1999/xhtml}html, {http://www.w3.org/1999/xhtml}body# 使用限定标签名查找元素for el in html_element.iter('{http://www.w3.org/1999/xhtml}*'):    print(el.tag)  # 输出: {http://www.w3.org/1999/xhtml}html, {http://www.w3.org/1999/xhtml}body# 查找没有命名空间的元素print([el.tag for el in html_element.iter('body')])  # 输出: []print([el.tag for el in html_element.iter('{}body') ])  # 输出: []print([el.tag for el in html_element.iter('{}*') ])  # 输出: []

总结

ElementTree API通过使用命名空间而不是前缀,提供了一种更加灵活和可靠的方式来处理XML标签。命名空间的管理可以显著提高代码的可维护性和可读性。通过合理使用nsmap和QName助手类,可以更方便地处理带命名空间的XML树。此外,ElementTree在属性处理和XPath查询中都提供了强大的命名空间支持,帮助开发者更高效地管理复杂的XML文档。

转载地址:http://ycicz.baihongyu.com/

你可能感兴趣的文章
python | gunicorn,一个非常实用的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>
python | huey,一个非常厉害的 任务调度 Python 库!
查看>>
python | hypothesis,一个有趣的 Python 库!
查看>>
python | Indico,一个超酷的 Python 库!
查看>>
python | isort,一个有趣的 自动整理导入语句 的Python 库!
查看>>
python | jinja,一个超酷的 Python 库!
查看>>
python | joblib,一个强大的 Python 库!
查看>>
python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
查看>>
python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
查看>>
python课程的中期报告范文_课题研究中期总结报告范文
查看>>
python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
查看>>
python | mplfinance,一个有趣的金融数据可视化 Python 库!
查看>>
python | nipy,一个强大的关于 神经影像数据分析 的Python 库!
查看>>
python | NLTK,一个强大的 自然语言处理 Python 库!
查看>>
python | nupic,一个强大的 处理时间序列的Python 库!
查看>>
python | orange3,一个神奇的 Python 库!
查看>>
python | pdfminer,一个神奇的 关于PDF 文件的 Python 库!
查看>>
python | pendulum,一个有趣的 日期和时间 Python 库!
查看>>
python | pluginbase,一个神奇的 关于插件框架 的Python 库!
查看>>