Home Backend Development Python Tutorial python操作xml文件详细介绍

python操作xml文件详细介绍

Jun 06, 2016 am 11:30 AM
python

关于python读取xml文章很多,但大多文章都是贴一个xml文件,然后再贴个处理文件的代码。这样并不利于初学者的学习,希望这篇文章可以更通俗易懂的教如何使用python 来读取xml 文件。

一、什么是xml?

xml即可扩展标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。

abc.xml

代码如下:




    4
   
        Python
       
            测试
       

   

   
        Zope
   


Ok ,从结构上,它很像我们常见的HTML超文本标记语言。但他们被设计的目的是不同的,超文本标记语言被设计用来显示数据,其焦点是数据的外观。它被设计用来传输和存储数据,其焦点是数据的内容。

那么它有如下特征:

首先,它是有标签对组成,

标签可以有属性:

标签对可以嵌入数据:abc

标签可以嵌入子标签(具有层级关系):

二、获得标签属性

那么,下面来介绍如何用python来读取这种类型的文件。

代码如下:


#coding=utf-8
import  xml.dom.minidom

#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')

#得到文档元素对象
root = dom.documentElement
print root.nodeName
print root.nodeValue
print root.nodeType
print root.ELEMENT_NODE

mxl.dom.minidom 模块被用来处理xml文件,所以要先引入。

xml.dom.minidom.parse() 用于打开一个xml文件,并将这个文件对象dom变量。

documentElement 用于得到dom对象的文档元素,并把获得的对象给root

每一个结点都有它的nodeName,nodeValue,nodeType属性。

nodeName为结点名字。

nodeValue是结点的值,只对文本结点有效。

nodeType是结点的类型。catalog是ELEMENT_NODE类型

现在有以下几种:

'ATTRIBUTE_NODE'
'CDATA_SECTION_NODE'
'COMMENT_NODE'
'DOCUMENT_FRAGMENT_NODE'
'DOCUMENT_NODE'
'DOCUMENT_TYPE_NODE'
'ELEMENT_NODE'
'ENTITY_NODE'
'ENTITY_REFERENCE_NODE'
'NOTATION_NODE'
'PROCESSING_INSTRUCTION_NODE'
'TEXT_NODE'


三、获得子标签

现在要获得catalog的子标签以的标签name

代码如下:




       4
      
              Python
            
                    测试
           

   

   
            Zope
   


对于知道元素名字的子元素,可以使用getElementsByTagName方法获取:

代码如下:


#coding=utf-8
import  xml.dom.minidom

#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')

#得到文档元素对象
root = dom.documentElement

bb = root.getElementsByTagName('maxid')
b= bb[0]
print b.nodeName

bb = root.getElementsByTagName('login')
b= bb[0]
print b.nodeName

如何区分相同标签名字的标签:

代码如下:




       4
      
              Python
            
                    测试
           

   

   
            Zope
   


标签不止一个如何区分?

代码如下:


#coding=utf-8
import  xml.dom.minidom

#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')

#得到文档元素对象
root = dom.documentElement

bb = root.getElementsByTagName('caption')
b= bb[2]
print b.nodeName

bb = root.getElementsByTagName('item')
b= bb[1]
print b.nodeName

root.getElementsByTagName('caption') 获得的是标签为caption 一组标签,b[0]表示一组标签中的第一个;b[2] ,表示这一组标签中的第三个。

四、获得标签属性值

代码如下:




       4
      
              Python
            
                    测试
           

   

   
            Zope
   


标签是有属性的,如何获得他们的属性?

代码如下:


#coding=utf-8
import  xml.dom.minidom

#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')

#得到文档元素对象
root = dom.documentElement

itemlist = root.getElementsByTagName('login')
item = itemlist[0]
un=item.getAttribute("username")
print un
pd=item.getAttribute("passwd")
print pd

ii = root.getElementsByTagName('item')
i1 = ii[0]
i=i1.getAttribute("id")
print i

i2 = ii[1]
i=i2.getAttribute("id")
print i

getAttribute方法可以获得元素的属性所对应的值。

五、获得标签对之间的数据

代码如下:




       4
      
              Python
            
                    测试
           

   

   
            Zope
   


标签对之间是有数据的,如何获得这些数据?

获得标签对之间的数据有多种方法,

方法一:

代码如下:


#coding=utf-8
import  xml.dom.minidom

#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')

#得到文档元素对象
root = dom.documentElement

cc=dom.getElementsByTagName('caption')
c1=cc[0]
print c1.firstChild.data

c2=cc[1]
print c2.firstChild.data

c3=cc[2]
print c3.firstChild.data

firstChild 属性返回被选节点的第一个子节点,.data表示获取该节点人数据。

方法二:

代码如下:


#coding=utf-8
from xml.etree import ElementTree as ET
per=ET.parse('abc.xml')
p=per.findall('./login/item')

for oneper in p:
    for child in oneper.getchildren():
        print child.tag,':',child.text


p=per.findall('./item')

for oneper in p:
    for child in oneper.getchildren():
        print child.tag,':',child.text

方法二有点复杂,所引用模块也与前面的不一样,findall用于指定在哪一级标签下开始遍历。

getchildren方法按照文档顺序返回所有子标签。并输出标签名(child.tag)和标签的数据(child.text)

其实,方法二的作用不在于此,它核心功能是可以遍历某一级标签下的所有子标签。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles