xml.etree.ElementTree --- ElementTree XML API?

源代碼: Lib/xml/etree/ElementTree.py


xml.etree.ElementTree 模塊實現了一個簡單高效的API,用于解析和創建XML數據。

在 3.3 版更改: 只要有可能,這個模塊將使用快速實現。xml.etree.cElementTree 模塊已棄用。

警告

xml.etree.ElementTree 模塊對于惡意構建的數據是不安全的。如果需要解析不可信或未經身份驗證的數據,請參見 XML 漏洞

教程?

這是一個使用 xml.etree.ElementTree (簡稱 ET )的簡短教程。目標是演示模塊的一些構建塊和基本概念。

XML樹和元素?

XML是一種固有的分層數據格式,最自然的表示方法是使用樹。為此, ET 有兩個類 ElementTree 將整個XML文檔表示為一個樹, Element 表示該樹中的單個節點。與整個文檔的交互(讀寫文件)通常在 ElementTree 級別完成。與單個XML元素及其子元素的交互是在 Element 級別完成的。

解析XML?

我們將使用以下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
'data'
>>> root.attrib
{}

它還有我們可以迭代的子節點:

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

子級是可以嵌套的,我們可以通過索引訪問特定的子級節點:

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

注解

并非XML輸入的所有元素都將作為解析樹的元素結束。目前,此模塊跳過輸入中的任何XML注釋、處理指令和文檔類型聲明。然而,使用這個模塊的API而不是從XML文本解析構建的樹可以包含注釋和處理指令,生成XML輸出時同樣包含這些注釋和處理指令。可以通過將自定義 TreeBuilder 實例傳遞給 XMLParser 構造函數來訪問文檔類型聲明。

Pull API進行非阻塞解析?

此模塊所提供了大多數解析函數都要求在返回任何結果之前一次性讀取整個文檔。 可以使用 XMLParser 并以漸進方式添加數據,但這是在回調目標上調用方法的推送式 API。 有時用戶真正想要的是能夠以漸進方式解析 XML 而無需阻塞操作,同時享受完整的已構造 Element 對象。

針對此需求的最強大工具是 XMLPullParser。 它不要求通過阻塞式讀取來獲得 XML 數據,而是通過執行 XMLPullParser.feed() 調用來漸進式地添加數據。 要獲得已解析的 XML 元素,應調用 XMLPullParser.read_events()。 下面是一個示例:

>>> parser = ET.XMLPullParser(['start', 'end'])
>>> parser.feed('<mytag>sometext')
>>> list(parser.read_events())
[('start', <Element 'mytag' at 0x7fa66db2be58>)]
>>> parser.feed(' more text</mytag>')
>>> for event, elem in parser.read_events():
...     print(event)
...     print(elem.tag, 'text=', elem.text)
...
end

常見的用例是針對以非阻塞方式進行的應用程序,其中 XML 是從套接字接收或從某些存儲設備漸進式讀取的。 在這些用例中,阻塞式讀取是不可接受的。

因為其非常靈活,XMLPullParser 在更簡單的用例中使用起來可能并不方便。 如果你不介意你的應用程序在讀取 XML 數據時造成阻塞但仍希望具有增量解析能力,可以考慮 iterparse()。 它在你讀取大型 XML 文檔并且不希望將它完全放去內存時會很適用。

尋找有趣的元素?

Element 有一些很有效的方法,可幫助遞歸遍歷其下的所有子樹(包括子級,子級的子級,等等)。例如 Element.iter():

>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}

Element.findall() 僅查找當前元素的直接子元素中帶有指定標簽的元素。 Element.find() 找帶有特定標簽的 第一個 子級,然后可以用 Element.text 訪問元素的文本內容。 Element.text 訪問元素的屬性:

>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68

通過使用 XPath ,可以更精確地指定要查找的元素。

修改XML文件?

ElementTree 提供了一種構建XML文檔并將其寫入文件的簡單方法。 ElementTree.write() 方法可達到此目的。

創建后可以直接操作 Element 對象。例如:使用 Element.text 修改文本字段,使用 Element.set() 方法添加和修改屬性,以及使用 Element.append() 添加新的子元素。

假設我們要在每個國家/地區的中添加一個排名,并在rank元素中添加一個 updated 屬性:

>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')

生成的XML現在看起來像這樣:

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

可以使用 Element.remove() 刪除元素。假設我們要刪除排名高于50的所有國家/地區:

>>> for country in root.findall('country'):
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')

生成的XML現在看起來像這樣:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>

構建XML文檔?

SubElement() 函數還提供了一種便捷方法來為給定元素創建新的子元素:

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>

使用命名空間解析XML?

如果 XML 輸入帶有 命名空間,則具有前綴的 prefix:sometag 形式的標記和屬性將被擴展為 {uri}sometag,其中 prefix 會被完整 URI 所替換。 并且,如果存在 默認命名空間,則完整 URI 會被添加到所有未加前綴的標記之前。

下面的 XML 示例包含兩個命名空間,一個具有前綴 "fictional" 而另一個則作為默認命名空間:

<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>

搜索和探查這個 XML 示例的一種方式是手動為 find()findall() 的 xpath 中的每個標記或屬性添加 URI:

root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
    name = actor.find('{http://people.example.com}name')
    print(name.text)
    for char in actor.findall('{http://characters.example.com}character'):
        print(' |-->', char.text)

一種更好的方式是搜索帶命名空間的 XML 示例創建一個字典來存放你自己的前綴并在搜索函數中使用它們:

ns = {'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)

這兩種方式都會輸出:

John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

其他資源?

請訪問 http://effbot.org/zone/element-index.htm 獲取教程和其他文檔的鏈接。

XPath支持?

此模塊提供了對 XPath 表達式 的有限支持用于在樹中定位元素。 其目標是支持一個簡化語法的較小子集;完整的 XPath 引擎超出了此模塊的適用范圍。

示例?

下面是一個演示此模塊的部分 XPath 功能的例子。 我們將使用來自 解析 XML 小節的 countrydata XML 文檔:

import xml.etree.ElementTree as ET

root = ET.fromstring(countrydata)

# Top-level elements
root.findall(".")

# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")

# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@name='Singapore']/year")

# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")

支持的XPath語法?

語法

含義

tag

Selects all child elements with the given tag. For example, spam selects all child elements named spam, and spam/egg selects all grandchildren named egg in all children named spam.

*

Selects all child elements. For example, */egg selects all grandchildren named egg.

.

選擇當前節點。這在路徑的開頭非常有用,用于指示它是相對路徑。

//

選擇所有子元素 在當前元素的所有下級中選擇所有下級元素。 例如,.//egg 是在整個樹中選擇所有 egg 元素。

..

選擇父元素。 如果路徑試圖前往起始元素的上級(元素的 find 被調用)則返回 None

[@attrib]

選擇具有給定屬性的所有元素。

[@attrib='value']

選擇給定屬性具有給定值的所有元素。該值不能包含引號。

[tag]

選擇所有包含 tag 子元素的元素。只支持直系子元素。

[.='text']

選擇完整文本內容等于 text 的所有元素(包括后代)。

3.7 新版功能.

[tag='text']

選擇所有包含名為 tag 的子元素的元素,這些子元素(包括后代)的完整文本內容等于給定的 text

[position]

選擇位于給定位置的所有元素。 位置可以是一個整數 (1 表示首位),表達式 last() (表示末位),或者相對于末位的位置 (例如 last()-1)。

謂詞(方括號內的表達式)之前必須帶有標簽名稱,星號或其他謂詞。position 謂詞前必須有標簽名稱。

參考?

函數?

xml.etree.ElementTree.Comment(text=None)?

注釋元素工廠函數。 這個工廠函數可創建一個特殊元素,它將被標準序列化器當作 XML 注釋來進行序列化。 注釋字串可以是字節串或是 Unicode 字符串。 text 是包含注釋字串的字符串。 返回一個表示注釋的元素實例。

請注意 XMLParser 會跳過輸入中的注釋而不會為其創建注釋對象。 ElementTree 將只在當使用某個 Element 方法向樹插入了注釋節點時才會包含注釋節點。

xml.etree.ElementTree.dump(elem)?

將一個元素樹或元素結構體寫入到 sys.stdout。 此函數應當只被用于調試。

實際輸出格式是依賴于具體實現的。 在這個版本中,它將以普通 XML 文件的格式寫入。

elem 是一個元素樹或單獨元素。

xml.etree.ElementTree.fromstring(text, parser=None)?

根據一個字符串常量解析 XML 的節。 與 XML() 類似。 text 是包含 XML 數據的字符串。 parser 是可選的解析器實例。 如果未給出,則會使用標準 XMLParser。 返回一個 Element 實例。

xml.etree.ElementTree.fromstringlist(sequence, parser=None)?

根據一個字符串片段序列解析 XML 文檔。 sequence 是包含 XML 數據片段的列表或其他序列對象。 parser 是可選的解析器實例。 如果未給出,則會使用標準的 XMLParser 解析器。 返回一個 Element 實例。

3.2 新版功能.

xml.etree.ElementTree.iselement(element)?

檢測一個對象是否為有效的元素對象。 element 是一個元素實例。 如果對象是一個元素對象則返回 True

xml.etree.ElementTree.iterparse(source, events=None, parser=None)?

Parses an XML section into an element tree incrementally, and reports what's going on to the user. source is a filename or file object containing XML data. events is a sequence of events to report back. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If events is omitted, only "end" events are reported. parser is an optional parser instance. If not given, the standard XMLParser parser is used. parser must be a subclass of XMLParser and can only use the default TreeBuilder as a target. Returns an iterator providing (event, elem) pairs.

請注意雖然 iterparse() 是以增量方式構建樹,但它會對 source (或其所指定的文件) 發出阻塞式讀取。 因此,它不適用于不可執行阻塞式讀取的應用。 對于完全非阻塞式的解析,請參看 XMLPullParser

注解

iterparse() 只會確保當發出 "start" 事件時看到了開始標記的 ">" 字符,因而在這個點上屬性已被定義,但文本容和末尾屬性還未被定義。 這同樣適用于元素的下級;它們可能存在也可能不存在。

如果你需要已完全填充的元素,請改為查找 "end" 事件。

3.4 版后已移除: parser 參數。

xml.etree.ElementTree.parse(source, parser=None)?

將一個 XML 的節解析為元素樹。 source 是包含 XML 數據的文件名或文件對象。 parser 是可選的解析器實例。 如果未給出,則會使用標準的 XMLParser 解析器。 返回一個 ElementTree 實例。

xml.etree.ElementTree.ProcessingInstruction(target, text=None)?

PI 元素工廠函數。 這個工廠函數可創建一個特殊元素,它將被當作 XML 處理指令來進行序列化。 target 是包含 PI 目標的字符串。 text 如果給出則是包含 PI 內容的字符串。 返回一個表示處理指令的元素實例。

請注意 XMLParser 會跳過輸入中的處理指令而不會為其創建注釋對象。 ElementTree 將只在當使用某個 Element 方法向樹插入了處理指令節點時才會包含處理指令節點。

xml.etree.ElementTree.register_namespace(prefix, uri)?

注冊一個命名空間前綴。 這個注冊表是全局的,并且任何對應給定前綴或命名空間 URI 的現有映射都會被移除。 prefix 是命名空間前綴。 uri 是命名空間 URI。 如果可能的話,這個命名空間中的標記和屬性將附帶給定的前綴來進行序列化。

3.2 新版功能.

xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)?

子元素工廠函數。 這個函數會創建一個元素實例,并將其添加到現有的元素。

元素名、屬性名和屬性值可以是字節串或 Unicode 字符串。 parent 是父元素。 tag 是子元素名。 attrib 是一個可選的字典,其中包含元素屬性。 extra 包含額外的屬性,以關鍵字參數形式給出。 返回一個元素實例。

xml.etree.ElementTree.tostring(element, encoding="us-ascii", method="xml", *, short_empty_elements=True)?

Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding 1 is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated). method is either "xml", "html" or "text" (default is "xml"). short_empty_elements has the same meaning as in ElementTree.write(). Returns an (optionally) encoded string containing the XML data.

3.4 新版功能: short_empty_elements 形參。

xml.etree.ElementTree.tostringlist(element, encoding="us-ascii", method="xml", *, short_empty_elements=True)?

Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding 1 is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated). method is either "xml", "html" or "text" (default is "xml"). short_empty_elements has the same meaning as in ElementTree.write(). Returns a list of (optionally) encoded strings containing the XML data. It does not guarantee any specific sequence, except that b"".join(tostringlist(element)) == tostring(element).

3.2 新版功能.

3.4 新版功能: short_empty_elements 形參。

xml.etree.ElementTree.XML(text, parser=None)?

根據一個字符串常量解析 XML 的節。 此函數可被用于在 Python 代碼中嵌入“XML 字面值”。 text 是包含 XML 數據的字符串。 parser 是可選的解析器實例。 如果未給出,則會使用標準的 XMLParser 解析器。 返回一個 Element 實例。

xml.etree.ElementTree.XMLID(text, parser=None)?

根據一個字符串常量解析 XML 的節,并且還將返回一個將元素的 id:s 映射到元素的字典。 text 是包含 XML 數據的字符串。 parser 是可選的解析器實例。 如果未給出,則會使用標準的 XMLParser 解析器。 返回一個包含 Element 實例和字典的元組。

XInclude 支持?

此模塊通過 xml.etree.ElementInclude 輔助模塊提供了對 XInclude 指令 的有限支持,這個模塊可被用來根據元素樹的信息在其中插入子樹和文本字符串。

示例?

以下是一個演示 XInclude 模塊用法的例子。 要在當前文本中包括一個 XML 文檔,請使用 {http://www.w3.org/2001/XInclude}include 元素并將 parse 屬性設為 "xml",并使用 href 屬性來指定要包括的文檔。

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="source.xml" parse="xml" />
</document>

默認情況下,href 屬性會被當作文件名來處理。 你可以使用自定義加載器來重載此行為。 還要注意標準輔助器不支持 XPointer 語法。

要處理這個文件,請正常加載它,并將根元素傳給 xml.etree.ElementTree 模塊:

from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()

ElementInclude.include(root)

ElementInclude 模塊使用來自 source.xml 文檔的根元素替代 {http://www.w3.org/2001/XInclude}include 元素。 結果看起來大概是這樣:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <para>This is a paragraph.</para>
</document>

如果省略了 parse 屬性,它會取默認的 "xml"。 要求有 href 屬性。

要包括文本文檔,請使用 {http://www.w3.org/2001/XInclude}include 元素,并將 parse 屬性設為 "text":

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) <xi:include href="year.txt" parse="text" />.
</document>

結果可能如下所示:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) 2003.
</document>

參考?

函數?

xml.etree.ElementInclude.default_loader(href, parse, encoding=None)?

默認的加載器。 這個默認的加載器會從磁盤讀取所包括的資源。 href 是一個 URL。 parse 是 "xml" 或 "text" 表示解析模式。 encoding 是可選的文本編碼格式。 如果未給出,則編碼格式為 utf-8。 返回已擴展的資源。 如果解析模式為 "xml",則它是一個 ElementTree 實例。 如果解析模式為 "text",則它是一個 Unicode 字符串。 如果加載器失敗,它可以返回 None 或者引發異常。

xml.etree.ElementInclude.include(elem, loader=None)?

This function expands XInclude directives. elem is the root element. loader is an optional resource loader. If omitted, it defaults to default_loader(). If given, it should be a callable that implements the same interface as default_loader(). Returns the expanded resource. If the parse mode is "xml", this is an ElementTree instance. If the parse mode is "text", this is a Unicode string. If the loader fails, it can return None or raise an exception.

元素對象?

class xml.etree.ElementTree.Element(tag, attrib={}, **extra)?

元素類。 這個類定義了 Element 接口,并提供了這個接口的引用實現。

元素名、屬性名和屬性值可以是字節串或 Unicode 字符串。 tag 是元素名。 attrib 是一個可選的字典,其中包含元素屬性。 extra 包含額外的屬性,以關鍵字參數形式給出。

tag?

一個標識此元素意味著何種數據的字符串(換句話說,元素類型)。

text?
tail?

這些屬性可被用于存放與元素相關聯的額外數據。 它們的值通常為字符串但也可以是任何應用專屬的對象。 如果元素是基于 XML 文件創建的,text 屬性會存放元素的開始標記及其第一個子元素或結束標記之間的文本,或者為 None,而 tail 屬性會存放元素的結束標記及下一個標記之間的文本,或者為 None。 對于 XML 數據

<a><b>1<c>2<d/>3</c></b>4</a>

a 元素的 texttail 屬性均為 Noneb 元素的 text"1"tail"4"c 元素的 text"2"tailNoned 元素的 textNonetail"3"

要獲取一個元素的內部文本,請參閱 itertext(),例如 "".join(element.itertext())

應用程序可以將任意對象存入這些屬性。

attrib?

一個包含元素屬性的字典。 請注意雖然 attrib 值總是一個真正可變的 Python 字典,但 ElementTree 實現可以選擇其他內部表示形式,并只在有需要時才創建字典。 為了發揮這種實現的優勢,請在任何可能情況下使用下列字典方法。

以下字典類方法可作用于元素屬性。

clear()?

重設一個元素。 此方法會移除所有子元素,清空所有屬性,并將 text 和 tail 屬性設為 None

get(key, default=None)?

獲取名為 key 的元素屬性。

返回屬性的值,或者如果屬性未找到則返回 default

items()?

將元素屬性以 (name, value) 對序列的形式返回。 所返回屬性的順序任意。

keys()?

將元素屬性名稱以列表的形式返回。 所返回名稱的順序任意。

set(key, value)?

將元素的 key 屬性設為 value

以下方法作用于元素的下級(子元素)。

append(subelement)?

將元素 subelement 添加到此元素的子元素內部列表。 如果 subelement 不是一個 Element 則會引發 TypeError

extend(subelements)?

使用具有零個或多個元素的序列對象添加 subelements。 如果某個子元素不是 Element 則會引發 TypeError

3.2 新版功能.

find(match, namespaces=None)?

Finds the first subelement matching match. match may be a tag name or a path. Returns an element instance or None. namespaces is an optional mapping from namespace prefix to full name.

findall(match, namespaces=None)?

Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order. namespaces is an optional mapping from namespace prefix to full name.

findtext(match, default=None, namespaces=None)?

Finds text for the first subelement matching match. match may be a tag name or a path. Returns the text content of the first matching element, or default if no element was found. Note that if the matching element has no text content an empty string is returned. namespaces is an optional mapping from namespace prefix to full name.

getchildren()?

3.2 版后已移除: Use list(elem) or iteration.

getiterator(tag=None)?

3.2 版后已移除: Use method Element.iter() instead.

insert(index, subelement)?

subelement 插入到此元素的給定位置中。 如果 subelement 不是一個 Element 則會引發 TypeError

iter(tag=None)?

創建一個以當前元素為根元素的樹的 iterator。 該迭代器將以文檔(深度優先)順序迭代此元素及其所有下級元素。 如果 tag 不為 None'*',則迭代器只返回標記為 tag 的元素。 如果樹結構在迭代期間被修改,則結果是未定義的。

3.2 新版功能.

iterfind(match, namespaces=None)?

根據標記名稱或者 路徑 查找所有匹配的子元素。 返回一個按文檔順序產生所有匹配元素的可迭代對象。 namespaces 是可選的從命名空間前綴到完整名稱的映射。

3.2 新版功能.

itertext()?

創建一個文本迭代器。 該迭代器將按文檔順序遍歷此元素及其所有子元素,并返回所有內部文本。

3.2 新版功能.

makeelement(tag, attrib)?

創建一個與此元素類型相同的新元素對象。 請不要調用此方法,而應改用 SubElement() 工廠函數。

remove(subelement)?

從元素中移除 subelement。 與 find* 方法不同的是此方法會基于實例的標識來比較元素,而不是基于標記的值或內容。

Element 對象還支持下列序列類型方法以配合子元素使用: __delitem__(), __getitem__(), __setitem__(), __len__()

注意:不帶子元素的元素將被檢測為 False。 此行為將在未來的版本中發生變化。 請改用 len(elem)elem is None 進行檢測。

element = root.find('foo')

if not element:  # careful!
    print("element not found, or element has no subelements")

if element is None:
    print("element not found")

ElementTree 對象?

class xml.etree.ElementTree.ElementTree(element=None, file=None)?

ElementTree 包裝器類。 這個類表示一個完整的元素層級結構,并添加了一些對于標準 XML 序列化的額外支持。

element 是根元素。 如果給出 XML file 則將使用其內容來初始化樹結構。

_setroot(element)?

替換該樹結構的根元素。 這將丟棄該樹結構的當前內容,并將其替換為給定的元素。 請小心使用。 element 是一個元素實例。

find(match, namespaces=None)?

Element.find() 類似,從樹的根節點開始。

findall(match, namespaces=None)?

Element.findall() 類似,從樹的根節點開始。

findtext(match, default=None, namespaces=None)?

Element.findtext() 類似,從樹的根節點開始。

getiterator(tag=None)?

3.2 版后已移除: Use method ElementTree.iter() instead.

getroot()?

返回這個樹的根元素。

iter(tag=None)?

創建并返回根元素的樹結構迭代器。 該迭代器會以節順序遍歷這個樹的所有元素。 tag 是要查找的標記(默認返回所有元素)。

iterfind(match, namespaces=None)?

Element.iterfind() 類似,從樹的根節點開始。

3.2 新版功能.

parse(source, parser=None)?

將一個外部 XML 節載入到此元素樹。 source 是一個文件名或 file objectparser 是可選的解析器實例。 如果未給出,則會使用標準的 XMLParser 解析器。 返回該節的根元素。

write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml", *, short_empty_elements=True)?

將元素樹以 XML 格式寫入到文件。 file 為文件名,或是以寫入模式打開的 file objectencoding 1 為輸出編碼格式 (默認為 US-ASCII)。 xml_declaration 控制是否要將 XML 聲明添加到文件中。 使用 False 表示從不添加,True 表示總是添加,None 表示僅在非 US-ASCII 或 UTF-8 或 Unicode 時添加 (默認為 None)。 default_namespace 設置默認 XML 命名空間 (用于 "xmlns")。 method"xml", "html""text" (默認為 "xml")。 僅限關鍵字形參 short_empty_elements 控制不包含內容的元素的格式。 如為 True (默認值),它們會被輸出為單個自結束標記,否則它們會被輸出為一對開始/結束標記。

輸出是一個字符串 (str) 或字節串 (bytes)。 由*encoding* 參數來控制。 如果 encoding"unicode",則輸出是一個字符串;否則為字節串;請注意這可能與 file 的類型相沖突,如果它是一個打開的 file object 的話;請確保你不會試圖寫入字符串到二進制流或者反向操作。

3.4 新版功能: short_empty_elements 形參。

這是將要被操作的 XML 文件:

<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>

修改第一段中的每個鏈接的 "target" 屬性的示例:

>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a"))   # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
>>> tree.write("output.xhtml")

QName 對象?

class xml.etree.ElementTree.QName(text_or_uri, tag=None)?

QName 包裝器。 這可被用來包裝 QName 屬性值,以便在輸出中獲得適當的命名空間處理。 text_or_uri 是一個包含 QName 值的字符串,其形式為 {uri}local,或者如果給出了 tag 參數,則為 QName 的 URI 部分。 如果給出了 tag,則第一個參數會被解讀為 URI,而這個參數會被解讀為本地名稱。 QName 實例是不透明的。

TreeBuilder 對象?

class xml.etree.ElementTree.TreeBuilder(element_factory=None)?

Generic element structure builder. This builder converts a sequence of start, data, and end method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format. element_factory, when given, must be a callable accepting two positional arguments: a tag and a dict of attributes. It is expected to return a new element instance.

close()?

刷新構建器緩存,并返回最高層級的文檔元素。 返回一個 Element 實例。

data(data)?

將文本添加到當前元素。 data 為要添加的文本。 這應當是一個字節串或 Unicode 字符串。

end(tag)?

結束當前元素。 tag 是元素名稱。 返回已結束的元素。

start(tag, attrs)?

打開一個新元素。 tag 是元素名稱。 attrs 是包含元素屬性的字典。 返回打開的元素。

In addition, a custom TreeBuilder object can provide the following method:

doctype(name, pubid, system)?

處理一條 doctype 聲明。 name 為 doctype 名稱。 pubid 為公有標識。 system 為系統標識。 此方法不存在于默認的 TreeBuilder 類中。

3.2 新版功能.

XMLParser對象?

class xml.etree.ElementTree.XMLParser(html=0, target=None, encoding=None)?

This class is the low-level building block of the module. It uses xml.parsers.expat for efficient, event-based parsing of XML. It can be fed XML data incrementally with the feed() method, and parsing events are translated to a push API - by invoking callbacks on the target object. If target is omitted, the standard TreeBuilder is used. The html argument was historically used for backwards compatibility and is now deprecated. If encoding 1 is given, the value overrides the encoding specified in the XML file.

3.4 版后已移除: The html argument. The remaining arguments should be passed via keyword to prepare for the removal of the html argument.

close()?

結束向解析器提供數據。 返回調用在構造期間傳入的 targetclose() 方法的結果;在默認情況下,這是最高層級的文檔元素。

doctype(name, pubid, system)?

3.2 版后已移除: Define the TreeBuilder.doctype() method on a custom TreeBuilder target.

feed(data)?

將數據送入解析器。 data 是編碼后的數據。

XMLParser.feed() calls target's start(tag, attrs_dict) method for each opening tag, its end(tag) method for each closing tag, and data is processed by method data(data). XMLParser.close() calls target's method close(). XMLParser can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file:

>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4

XMLPullParser對象?

class xml.etree.ElementTree.XMLPullParser(events=None)?

A pull parser suitable for non-blocking applications. Its input-side API is similar to that of XMLParser, but instead of pushing calls to a callback target, XMLPullParser collects an internal list of parsing events and lets the user read from it. events is a sequence of events to report back. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If events is omitted, only "end" events are reported.

feed(data)?

將給定的字節數據送入解析器。

close()?

通知解析器數據流已終結。 不同于 XMLParser.close(),此方法總是返回 None。 當解析器被關閉時任何還未被獲取的事件仍可通過 read_events() 被讀取。

read_events()?

Return an iterator over the events which have been encountered in the data fed to the parser. The iterator yields (event, elem) pairs, where event is a string representing the type of event (e.g. "end") and elem is the encountered Element object.

在之前對 read_events() 的調用中提供的事件將不會被再次產生。 事件僅當它們從迭代器中被取出時才會在內部隊列中被消費,因此多個讀取方對獲取自 read_events() 的迭代器進行平行迭代將產生無法預料的結果。

注解

XMLPullParser 只會確保當發出 "start" 事件時看到了開始標記的 ">" 字符,因而在這個點上屬性已被定義,但文本內容和末尾屬性還未被定義。 這同樣適用于元素的下級;它們可能存在也可能不存在。

如果你需要已完全填充的元素,請改為查找 "end" 事件。

3.4 新版功能.

異常?

class xml.etree.ElementTree.ParseError?

XML 解析器錯誤,由此模塊中的多個解析方法在解析失敗時引發。 此異常的實例的字符串表示將包含用戶友好的錯誤消息。 此外,它將具有下列可用屬性:

code?

來自外部解析器的數字錯誤代碼。 請參閱 xml.parsers.expat 的文檔查看錯誤代碼列表及它們的含義。

position?

一個包含 line, column 數值的元組,指明錯誤發生的位置。

備注

1(1,2,3,4)

包括在 XML 輸出中的編碼格式字符串應當符合適當的標準。 例如 "UTF-8" 是有效的,但 "UTF8" 是無效的。 請參閱 https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDeclhttps://www.iana.org/assignments/character-sets/character-sets.xhtml