Python对XML文件实现增删改查操作

 更新时间:2022年11月10日 14:54:19   作者:Septieme  
这篇文章主要为大家详细介绍了Python对XML文件进行实现增删改查操作的方法,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的可以了解一下

PYTHON 操作 XML

读取XML文件

关于XML的介绍

<data> 与 </data> 是一对标签的开始与结束

<property … /> 也是一个正确的标签,以 /> 结尾,是在标签没有嵌套内容时的简写形式

name=“cat”,name是<data>标签的一个属性,cat是name属性的值

description here …是<data>标签的内容,这里是一段文本。当然也可以是xml的嵌套

<data name="cat" num="10"> description here ... </data>

<property value="node" />

<country name="china">
	<province name="beijing">
		<school name="the sunshine school" />
	</province>
</country>

准备一个demo.xml文件

<data>
    <teacher name="Albert">
        <birthday>1980</birthday>
        <gender>male</gender>
        <subject>Math</subject>
    </teacher>

    <student name="Becky">
        <birthday>2000</birthday>
        <gender>female</gender>
        <hobbies>
            <hobby>skating</hobby>
            <hobby>rocks</hobby>
        </hobbies>
        <exam absence="no">
            <math>90</math>
            <english>90</english>
            <music>95</music>
        </exam>

    </student>
    <student name="Cindy">
        <birthday>2001</birthday>
        <gender>female</gender>
        <hobbies>
            <hobby>reading</hobby>
            <hobby>guitar</hobby>
        </hobbies>
        <exam absence="yes">
        </exam>
    </student>

    <student name="Duke">
        <birthday>2000</birthday>
        <gender>male</gender>
        <hobbies>
            <hobby>football</hobby>
            <hobby>surfing</hobby>
        </hobbies>
        <exam absence="no">
            <math>100</math>
            <english>80</english>
            <music>92</music>
        </exam>
    </student>

</data>

读取xml文件内容

# Read the .xml file
tree = ET.parse("demo.xml")
root = tree.getroot()
print(root)

结果

<Element 'data' at 0x102d80cf8>

遍历XML元素

for … in … 可以遍历当前元素的所有直接子节点

for n in root:
    # items() returns all <key, value> pairs of the tag
    print(n, n.tag , n.attrib, n.items())

结果

(<Element 'teacher' at 0x1048b9e48>, 'teacher', {'name': 'Albert'}, [('name', 'Albert')])
(<Element 'student' at 0x1048bf0f0>, 'student', {'name': 'Becky'}, [('name', 'Becky')])
(<Element 'student' at 0x1048bf3c8>, 'student', {'name': 'Cindy'}, [('name', 'Cindy')])
(<Element 'student' at 0x1048bf5f8>, 'student', {'name': 'Duke'}, [('name', 'Duke')])

想要迭代遍历当前元素的所有子节点(包括子孙节点)

for n in root.iter():
    print(n, n.tag)

结果

(<Element 'data' at 0x1052f0cf8>, 'data')
(<Element 'teacher' at 0x1052f0e48>, 'teacher')
(<Element 'birthday' at 0x1052f0d30>, 'birthday')
(<Element 'gender' at 0x1052f6080>, 'gender')
(<Element 'subject' at 0x1052f60b8>, 'subject')
(<Element 'student' at 0x1052f60f0>, 'student')
(<Element 'birthday' at 0x1052f6048>, 'birthday')
(<Element 'gender' at 0x1052f6128>, 'gender')
(<Element 'hobbies' at 0x1052f6198>, 'hobbies')
(<Element 'hobby' at 0x1052f6208>, 'hobby')
(<Element 'hobby' at 0x1052f6240>, 'hobby')
(<Element 'exam' at 0x1052f62b0>, 'exam')
(<Element 'math' at 0x1052f6320>, 'math')
(<Element 'english' at 0x1052f6390>, 'english')
(<Element 'music' at 0x1052f6400>, 'music')
(<Element 'student' at 0x1052f63c8>, 'student')
(<Element 'birthday' at 0x1052f6438>, 'birthday')
(<Element 'gender' at 0x1052f6470>, 'gender')
(<Element 'hobbies' at 0x1052f64a8>, 'hobbies')
(<Element 'hobby' at 0x1052f6518>, 'hobby')
(<Element 'hobby' at 0x1052f6588>, 'hobby')
(<Element 'exam' at 0x1052f65c0>, 'exam')
(<Element 'student' at 0x1052f65f8>, 'student')
(<Element 'birthday' at 0x1052f6630>, 'birthday')
(<Element 'gender' at 0x1052f6668>, 'gender')
(<Element 'hobbies' at 0x1052f66a0>, 'hobbies')
(<Element 'hobby' at 0x1052f6710>, 'hobby')
(<Element 'hobby' at 0x1052f6780>, 'hobby')
(<Element 'exam' at 0x1052f67b8>, 'exam')
(<Element 'math' at 0x1052f6828>, 'math')
(<Element 'english' at 0x1052f6898>, 'english')
(<Element 'music' at 0x1052f6908>, 'music')

想要选择性地迭代直接子节点

for n in root.iter('teacher'):
    print(n, n.tag)
(<Element 'teacher' at 0x100f29e48>, 'teacher')

查找XML元素

find与findall查找xml元素

# find the first element
print(root.find('student'))
# find all  elements
print(root.findall('student'))
<Element 'student' at 0x1034300f0>

[<Element 'student' at 0x1034300f0>, <Element 'student' at 0x1034303c8>, <Element 'student' at 0x1034305f8>]

demo

for n in root:
    if n.tag == 'student' and n.get('name') == 'Becky':
        exam_node = n.find('exam')
        for subject in exam_node:
            print(subject.tag + " " + subject.text)

结果

math 90
english 90
music 95

添加XML元素

p = ET.Element(tag_name)

demo

for n in root:
    if n.tag == 'student' and n.get('name') == 'Cindy':
        exam_node = n.find('exam')
        exam_node.set("absence", "no")
        for subject in ['math', 'music']:
            p = ET.Element(subject)
            p.text = '90'
            exam_node.append(p)

if os.path.exists('new.xml'):
    os.remove('new.xml')
tree.write('new.xml', encoding='utf-8', xml_declaration=True)

结果

    <student name="Cindy">
        <birthday>2001</birthday>
        <gender>female</gender>
        <hobbies>
            <hobby>reading</hobby>
            <hobby>guitar</hobby>
        </hobbies>
        <exam absence="no">
        <math>90</math><music>90</music></exam>
    </student>

修改XML元素

demo

for n in root:
    if n.tag == 'student' and n.get('name') == 'Cindy':
        exam_node = n.find('exam')
        exam_node.set("absence", "no")
        exam_node.set("date", "2022-11-11")
        for subject in ['math', 'music']:
            p = ET.Element(subject)
            p.text = '90'
            exam_node.append(p)

        hobbies_node = n.find('hobbies').findall("hobby")
        hobbies_node[0].text = 'piano'
        p = ET.Element("hobby")
        p.set("old_hobby", 'yes')
        p.text = 'reading'
        n.find('hobbies').remove(hobbies_node[1])
        n.find('hobbies').append(p)

结果

    <student name="Cindy">
        <birthday>2001</birthday>
        <gender>female</gender>
        <hobbies>
            <hobby>piano</hobby>
            <hobby old_hobby="yes">reading</hobby></hobbies>
        <exam absence="no" date="2022-11-11">
        <math>90</math><music>90</music></exam>
    </student>

到此这篇关于Python对XML文件实现增删改查操作的文章就介绍到这了,更多相关Python XML增删改查内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Django之模板层的实现代码

    Django之模板层的实现代码

    这篇文章主要介绍了Django之模板层的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • python模拟登陆网站的示例

    python模拟登陆网站的示例

    这篇文章主要介绍了python模拟登陆网站的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-03-03
  • pytorch tensor int型除法出现的问题

    pytorch tensor int型除法出现的问题

    这篇文章主要介绍了pytorch tensor int型除法出现的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-04-04
  • 基于PyInstaller各参数的含义说明

    基于PyInstaller各参数的含义说明

    这篇文章主要介绍了基于PyInstaller各参数的含义说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • python实现井字棋游戏

    python实现井字棋游戏

    这篇文章主要为大家详细介绍了python实现井字棋游戏的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • python可以用哪些数据库

    python可以用哪些数据库

    在本篇文章里小编给大家整理的是关于python支持哪些数据库的相关知识点内容,有兴趣的朋友们可以学习下。
    2020-06-06
  • scrapy爬虫完整实例

    scrapy爬虫完整实例

    这篇文章主要介绍了scrapy爬虫完整实例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 使用Python模块进行数据处理的详细步骤

    使用Python模块进行数据处理的详细步骤

    Python 提供了丰富的模块和库,用于处理各种类型的数据,本文介绍了一些常用的模块和库,以及如何使用它们进行数据处理的详细步骤和代码示例,对我们的学习或工作有一定的帮助,需要的朋友可以参考下
    2025-02-02
  • python脚本实现分析dns日志并对受访域名排行

    python脚本实现分析dns日志并对受访域名排行

    这篇文章主要介绍了python脚本实现分析dns日志并对受访域名排行,本文是在Windows服务器环境中实现,需要的朋友可以参考下
    2014-09-09
  • 一文详解Python如何优雅地对数据进行分组

    一文详解Python如何优雅地对数据进行分组

    这篇文章主要和大家详细介绍一下Python是如何优雅地对数据进行分组的,文中通过示例进行了详细的讲解,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-07-07

最新评论