Python

Python 操作 DOM(待更)

2020-11-20  本文已影响0人  水之心

XML 简介

xml.etree.ElementTree 模块实现了一个简单高效的API,用于解析和创建XML数据。

XML是一种固有的分层数据格式,最自然的表示方法是使用树。ET(xml.etree.ElementTree ) 有两个类: ElementTree 将整个XML文档表示为一个树, Element 表示该树中的单个节点。与整个文档的交互(读写文件)通常在 ElementTree 级别完成。与单个XML元素及其子元素的交互是在 Element 级别完成的。

解析XML

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

可以通过从文件中读取来导入此数据:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

或直接从字符串中解析:

root = ET.fromstring(country_data_as_string)

fromstring() 将XML从字符串直接解析为 Element ,该元素是已解析树的根元素。其他解析函数可能会创建一个 ElementTree 。更多信息请查阅文档。

作为 Elementroot 具有标签和属性字典:

root.tag, root.attrib
('data', {})

还有可以迭代的子节点:

for child in root:
    print(child.tag, child.attrib)
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

子级是可以嵌套的,我们可以通过索引访问特定的子级节点:

root[0][1].text
'2008'

Element

Element实例元素的长度是其子元素的数量。那意味着如果你要检查元素是否真的为空,则应同时检查它的长度和它的text属性。元素标签,属性名称和属性值可以是字节或字符串。

Element 是一个灵活的容器对象,旨在将分层数据结构存储在内存中。可以说是 listdict 之间的交叉。每个元素都有许多与之关联的属性:

例如:<tag attrib>text<child/>...</tag>tail

def __init__(self, tag, attrib={}, **extra):
        if not isinstance(attrib, dict):
            raise TypeError("attrib must be dict, not %s" % (
                attrib.__class__.__name__,))
        self.tag = tag
        self.attrib = {**attrib, **extra}
        self._children = []

要创建元素实例,请使用Element构造函数或SubElement工厂函数。您还可以使用ElementTree类包装元素结构,并将其与 XML 相互转换。

attrib = {'id': 'root'}
extra = {'name': 'root'}
tag = 'html'
html = ET.Element(tag, attrib, **extra)
html
<Element 'html' at 0x000001DD3726B540>
len(html) # 子元素为 0
0

创建子元素

tag2 = 'body'
attrib2 = {'name': 'body'}
# 创建新的元素
body = html.makeelement(tag2, attrib2) 
# 将 body 作为 html 的子元素
html.append(body)

len(html) # 子元素添加
1

考虑到元素的可拓展性,最好使用 SubElement 工厂函数,来生成子元素。上面的子元素可以这样生成:

body = ET.SubElement(html, tag2, attrib2, **extra)
body
<Element 'body' at 0x000001DD369DA770>
上一篇下一篇

猜你喜欢

热点阅读