用法:
class xml.etree.ElementTree.Element(tag, attrib={}, **extra)
元素類。該類定義了 Element 接口,並提供了該接口的參考實現。
元素名稱、屬性名稱和屬性值可以是字節字符串或 Unicode 字符串。
tag
是元素名稱。attrib
是一個可選字典,包含元素屬性。extra
包含附加屬性,作為關鍵字參數給出。以下 dictionary-like 方法適用於元素屬性。
以下方法適用於元素的子元素(子元素)。
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")
在 Python 3.8 之前,元素的 XML 屬性的序列化順序是通過按屬性名稱排序來人為地預測的。基於現在保證的 dicts 排序,這種任意重新排序在 Python 3.8 中被刪除,以保留屬性最初由用戶代碼解析或創建的順序。
一般來說,用戶代碼應該盡量不依賴於特定的屬性順序,因為XML Information Set 明確地排除了傳遞信息的屬性順序。代碼應該準備好處理輸入的任何排序。在需要確定性 XML 輸出的情況下,例如對於加密簽名或測試數據集,
canonicalize()
函數可使用規範序列化。在規範輸出不適用但輸出仍需要特定屬性順序的情況下,代碼應旨在以所需順序直接創建屬性,以避免代碼讀者感知不匹配。在難以實現的情況下,可以在序列化之前應用如下配方,以獨立於元素創建來強製執行訂單:
def reorder_attributes(root): for el in root.iter(): attrib = el.attrib if len(attrib) > 1: # adjust attribute order, e.g. by sorting attribs = sorted(attrib.items()) attrib.clear() attrib.update(attribs)
相關用法
- Python xml.etree.ElementTree.XMLParser用法及代碼示例
- Python xml.etree.ElementTree.canonicalize用法及代碼示例
- Python xml.parsers.expat.ExpatError.code用法及代碼示例
- Python xml.parsers.expat.ParserCreate用法及代碼示例
- Python xml.dom.pulldom.DOMEventStream.expandNode用法及代碼示例
- Python xdrlib.Packer.pack_list用法及代碼示例
- Python cudf.core.column.string.StringMethods.is_vowel用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python sklearn.cluster.MiniBatchKMeans用法及代碼示例
- Python pandas.arrays.IntervalArray.is_empty用法及代碼示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
- Python dask.dataframe.Series.apply用法及代碼示例
- Python networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path用法及代碼示例
- Python scipy.ndimage.binary_opening用法及代碼示例
- Python pyspark.pandas.Series.dropna用法及代碼示例
- Python torchaudio.transforms.Fade用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 xml.etree.ElementTree.Element。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。