Python解析XML文本技术详解:模块使用与正则表达式匹配技巧

[id_10643864]id_[id_722453216]702338126]

Python解析XML文本技术详解:模块使用与正则表达式匹配技巧

说明 导入模块

import xml.etree.ElementTree as ET
import re

xml文本

若要显示正确的 xml 文本格式,可使用在线的 xml 文本编辑器,比如菜鸟教程 xml 在线编辑器。

[id_661727268]
str_xml = """

    
        Event
        
    
    
        
    

"""
# 不带有命名空间的xml文本
str_xml_without_space = """

    
        1
        2008
        141100
        
        
    
    
        4
        2011
        59900
        
    
    
        68
        2011
        13600
        
        
    
"""

详细代码示例

# 解析不带有命名空间的文本
root1 = ET.fromstring(str_xml_without_space)
print(root1)
print(root1.findall('./country')[0].attrib)
# 解析带有命名空间的文本
root_space = ET.fromstring(str_xml)
print(root_space.tag)
# 检查xml文本中是否带有命名空间
xml_space = re.findall(r"{\S+}", root_space.tag)[0]
if xml_space:
    print('xml space:' + xml_space)
else:
    xml_space = ''
    print(在字符串中未找到命名空间。)
在有命名空间的文件里,如果没有添加命名空间,那么就找不到相应的结果。
使用 root_space.findall('.')[0] 获取的元素的属性。
查找 root_space 中所有的 "./" ,是通过 findall 来实现的。
通过 root_space 去查找 "." ,接着把查找到的内容打印出来。
打印('root text: ' + root_space.findtext('./'))
root_li = root_space.findall(".//{0}li".format(xml_space))
for _index in root_li:
    print('tag: ' + _index.tag)
    print('attrib: ' + str(_index.attrib['title']))
    if _index.findall('./{0}a'.format(xml_space)):
        print(_index.findall('./{0}a'.format(xml_space))[0].attrib['href'].split(';')[0])
    if _index.findall('./{0}span'.format(xml_space)):
        print(_index.findall('./{0}span'.format(xml_space))[0].text)
        print(_index.findall('./{0}span'.format(xml_space))[1].text)
print(root_space.findall("./{0}body".format(xml_space)))

技术细节

xml 模块主要被用于解析 xml 文本,正则表达式模块 re 则用于匹配 xml 文件是否使用了命名空间。如果使用了命名空间,就将其提取出来以便后续使用。

解析 xml 文件时需要知晓 xml 的语法格式、标签、属性、内容以及尾等方面,同时还需要掌握 xpath 的语法,以便能够正确地提取到相应的文本信息。

xpath 语法在官方的 xml 文档中能够找到详细的说明,其参考地址为 xml 官方文档说明。

小结

此处的 xml 文档解析主要是通过示例来知晓 xml 模块的用法以及一些简单示例。若想要更深入地了解相关信息,那就查看官方文档。

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

23阅读