加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml.etree.ElementTree — The ElementTree XML API

发布时间:2020-12-16 00:18:52 所属栏目:百科 来源:网络整理
导读:New in version 2.5. Source code: Lib/xml/etree/ElementTree.py The Element type is a flexible container object,designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary. W


New in version 2.5.

Source code:Lib/xml/etree/ElementTree.py


TheElementtype is a flexible container object,designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary.

Warning

Thexml.etree.ElementTreemodule is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data seeXML vulnerabilities.

Each element has a number of properties associated with it:

  • a tag which is a string identifying what kind of data this element represents (the element type,in other words).
  • a number of attributes,stored in a Python dictionary.
  • a text string.
  • an optional tail string.
  • a number of child elements,stored in a Python sequence

To create an element instance,use theElementconstructor or theSubElement()factory function.

TheElementTreeclass can be used to wrap an element structure,and convert it from and to XML.

A C implementation of this API is available asxml.etree.cElementTree.

Seehttp://effbot.org/zone/element-index.htmfor tutorials and links to other docs. Fredrik Lundh’s page is also the location of the development version of the xml.etree.ElementTree.

Changed in version 2.7:The ElementTree API is updated to 1.3. For more information,seeIntroducing ElementTree 1.3.

19.7.1. Tutorial

This is a short tutorial for usingxml.etree.ElementTree(ETin short). The goal is to demonstrate some of the building blocks and basic concepts of the module.

19.7.1.1. XML tree and elements

XML is an inherently hierarchical data format,and the most natural way to represent it is with a tree.EThas two classes for this purpose -ElementTreerepresents the whole XML document as a tree,andElementrepresents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on theElementTreelevel. Interactions with a single XML element and its sub-elements are done on theElementlevel.

19.7.1.2. Parsing XML

We’ll be using the following XML document as the sample data for this section:

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

We have a number of ways to import the data. Reading the file from disk:

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

Reading the data from a string:

root .fromstring(country_data_as_string)

fromstring()parses XML from a string directly into anElement,which is the root element of the parsed tree. Other parsing functions may create anElementTree. Check the documentation to be sure.

As anroothas a tag and a dictionary of attributes:

>>>
>>> root.tag
'data'
.attrib
{}

It also has children nodes over which we can iterate:

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

Children are nested,and we can access specific child nodes by index:

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

19.7.1.3. Finding interesting elements

Elementhas some useful methods that help iterate recursively over all the sub-tree below it (its children,their children,and so on). For example,Element.iter():

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

Element.findall()finds only elements with a tag which are direct children of the current element.Element.find()finds thefirstchild with a particular tag,andElement.textaccesses the element’s text content.Element.get()accesses the element’s attributes:

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

More sophisticated specification of which elements to look for is possible by usingXPath.

19.7.1.4. Modifying an XML File

ElementTreeprovides a simple way to build XML documents and write them to files. TheElementTree.write()method serves this purpose.

Once created,anElementobject may be manipulated by directly changing its fields (such asElement.text),adding and modifying attributes (Element.set()method),as well as adding new children (for example withElement.append()).

Let’s say we want to add one to each country’s rank,and add anupdatedattribute to the rank element:

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

Our XML now looks like this:

<rank updated="yes">2>5>69</data>

We can remove elements usingElement.remove(). Let’s say we want to remove all countries with a rank higher than 50:

int(country.text) if rank > 50: ... root.remove(country) </data>

19.7.1.5. Building XML documents

TheSubElement()function also provides a convenient way to create new sub-elements for a given element:

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

19.7.1.6. Additional resources

Seehttp://effbot.org/zone/element-index.htmfor tutorials and links to other docs.

19.7.2. XPath support

This module provides limited support forXPath expressionsfor locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.

19.7.2.1. Example

Here’s an example that demonstrates some of the XPath capabilities of the module. We’ll be using thecountrydataXML document from theParsing XMLsection:

ET root .fromstring(countrydata) # Top-level elements root".") # All 'neighbor' grand-children of 'country' children of the top-level # elements root"./country/neighbor") # Nodes with name='Singapore' that have a 'year' child root".//year/..[@name='Singapore']") # 'year' nodes that are children of nodes with name='Singapore' root".//*[@name='Singapore']/year") # All 'neighbor' nodes that are the second child of their parent root".//neighbor[2]")

19.7.2.2. Supported XPath syntax

Syntax Meaning
tag Selects all child elements with the given tag. For example,243)">spamselects all child elements namedspam,andspam/eggselects all grandchildren namedeggin all children namedspam.
* Selects all child elements. For example,243)">*/eggselects all grandchildren namedegg.
. Selects the current node. This is mostly useful at the beginning of the path,to indicate that it’s a relative path.
// Selects all subelements,on all levels beneath the current element. For example,243)">.//eggselects alleggelements in the entire tree.
.. Selects the parent element.
[@attrib] Selects all elements that have the given attribute.
[@attrib='value'] Selects all elements for which the given attribute has the given value. The value cannot contain quotes.
[tag] Selects all elements that have a child namedtag. Only immediate children are supported.
[position] Selects all elements that are located at the given position. The position can be either an integer (1 is the first position),the expressionlast()(for the last position),or a position relative to the last position (e.g.last()-1).

Predicates (expressions within square brackets) must be preceded by a tag name,an asterisk,or another predicate.positionpredicates must be preceded by a tag name.

19.7.3. Reference

19.7.3.1. Functions

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

Comment element factory. This factory function creates a special element that will be serialized as an XML comment by the standard serializer. The comment string can be either a bytestring or a Unicode string.textis a string containing the comment string. Returns an element instance representing a comment.

xml.etree.ElementTree. dump ( elem )

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version,it’s written as an ordinary XML file.

elemis an element tree or an individual element.

xml.etree.ElementTree. fromstring ( text )

Parses an XML section from a string constant. Same asXML().textis a string containing XML data. Returns anElementinstance.

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

Parses an XML document from a sequence of string fragments.sequenceis a list or other sequence containing XML data fragments.parseris an optional parser instance. If not given,the standardXMLParserparser is used. Returns anElementinstance.

New in version 2.7.

xml.etree.ElementTree. iselement ( element )

Checks if an object appears to be a valid element object.elementis an element instance. Returns a true value if this is an element object.

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.sourceis a filename or file object containing XML data.eventsis a list of events to report back. If omitted,only “end” events are reported.parseris an optional parser instance. If not given,124); text-decoration:none" rel="nofollow">XMLParserparser is used.parseris not supported bycElementTree. Returns aniteratorproviding(event,elem)pairs.

Note

iterparse()only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event,so the attributes are defined,but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present.

If you need a fully populated element,look for “end” events instead.

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

Parses an XML section into an element tree.sourceis a filename or file object containing XML data.parseris an optional parser instance. If not given,124); text-decoration:none" rel="nofollow">XMLParserparser is used. Returns anElementTreeinstance.

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

PI element factory. This factory function creates a special element that will be serialized as an XML processing instruction.targetis a string containing the PI target.textis a string containing the PI contents,if given. Returns an element instance,representing a processing instruction.

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

Registers a namespace prefix. The registry is global,and any existing mapping for either the given prefix or the namespace URI will be removed.prefixis a namespace prefix.uriis a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix,if at all possible.

New in version 2.7.

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

Subelement factory. This function creates an element instance,and appends it to an existing element.

The element name,attribute names,and attribute values can be either bytestrings or Unicode strings.parentis the parent element.tagis the subelement name.attribis an optional dictionary,containing element attributes.extracontains additional attributes,given as keyword arguments. Returns an element instance.

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

Generates a string representation of an XML element,including all subelements.elementis anElementinstance.encoding[1]is the output encoding (default is US-ASCII).methodis either"xml",243)">"html"or"text"(default is"xml"). Returns an encoded string containing the XML data.

xml.etree.ElementTree. tostringlist ( element,method="xml" ) Elementinstance.encoding"xml"). Returns a list of encoded strings containing the XML data. It does not guarantee any specific sequence,except that"".join(tostringlist(element))==tostring(element).

New in version 2.7.

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

Parses an XML section from a string constant. This function can be used to embed “XML literals” in Python code.textis a string containing XML data.parseris an optional parser instance. If not given,124); text-decoration:none" rel="nofollow">Elementinstance.

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

Parses an XML section from a string constant,and also returns a dictionary which maps from element id:s to elements.textis a string containing XML data.parseris an optional parser instance. If not given,124); text-decoration:none" rel="nofollow">XMLParserparser is used. Returns a tuple containing anElementinstance and a dictionary.

19.7.3.2. Element Objects

class xml.etree.ElementTree. Element ( tag,**extra )

Element class. This class defines the Element interface,and provides a reference implementation of this interface.

The element name,and attribute values can be either bytestrings or Unicode strings.tagis the element name.attribis an optional dictionary,given as keyword arguments.

tag

A string identifying what kind of data this element represents (the element type,in other words).

text

Thetextattribute can be used to hold additional data associated with the element. As the name implies this attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found between the element tags.

tail

Thetailattribute can be used to hold additional data associated with the element. This attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found after the element’s end tag and before the next tag.

attrib

A dictionary containing the element’s attributes. Note that while theattribvalue is always a real mutable Python dictionary,an ElementTree implementation may choose to use another internal representation,and create the dictionary only if someone asks for it. To take advantage of such implementations,use the dictionary methods below whenever possible.

The following dictionary-like methods work on the element attributes.

clear ( )

Resets an element. This function removes all subelements,clears all attributes,and sets the text and tail attributes to None.

get ( key,default=None )

Gets the element attribute namedkey.

Returns the attribute value,ordefaultif the attribute was not found.

items ( )

Returns the element attributes as a sequence of (name,value) pairs. The attributes are returned in an arbitrary order.

keys ( )

Returns the elements attribute names as a list. The names are returned in an arbitrary order.

set ( key,value )

Set the attributekeyon the element tovalue.

The following methods work on the element’s children (subelements).

append ( subelement )

Adds the elementsubelementto the end of this elements internal list of subelements.

extend ( subelements )

Appendssubelementsfrom a sequence object with zero or more elements. RaisesAssertionErrorif a subelement is not a valid object.

New in version 2.7.

find ( match )

Finds the first subelement matchingmatch.matchmay be a tag name or path. Returns an element instance orNone.

findall ( match )

Finds all matching subelements,by tag name or path. Returns a list containing all matching elements in document order.

findtext ( match,default=None )

Finds text for the first subelement matchingmatch.matchmay be a tag name or path. Returns the text content of the first matching element,ordefaultif no element was found. Note that if the matching element has no text content an empty string is returned.

getchildren ( )

Deprecated since version 2.7:Uselist(elem)or iteration.

getiterator ( tag=None )

Deprecated since version 2.7:Use methodElement.iter()instead.

insert ( index,element )

Inserts a subelement at the given position in this element.

iter ( tag=None )

Creates a treeiteratorwith the current element as the root. The iterator iterates over this element and all elements below it,in document (depth first) order. Iftagis notNoneor'*',only elements whose tag equalstagare returned from the iterator. If the tree structure is modified during iteration,the result is undefined.

New in version 2.7.

iterfind ( match )

New in version 2.7.

itertext ( )

Creates a text iterator. The iterator loops over this element and all subelements,in document order,and returns all inner text.

New in version 2.7.

makeelement ( tag,attrib )

Creates a new element object of the same type as this element. Do not call this method,use theSubElement()factory function instead.

remove ( subelement )

Removessubelementfrom the element. Unlike the find* methods this method compares elements based on the instance identity,not on tag value or contents.

Elementobjects also support the following sequence type methods for working with subelements:__delitem__(),__getitem__(),__setitem__(),__len__().

Caution: Elements with no subelements will test asFalse. This behavior will change in future versions. Use specificlen(elem)orelemisNonetest instead.

element = root'foo')

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

if element is None:
    "element not found"

19.7.3.3. ElementTree Objects

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

ElementTree wrapper class. This class represents an entire element hierarchy,and adds some extra support for serialization to and from standard XML.

elementis the root element. The tree is initialized with the contents of the XMLfileif given.

_setroot ( element )

Replaces the root element for this tree. This discards the current contents of the tree,and replaces it with the given element. Use with care.elementis an element instance.

find ( match )

Same asElement.find(),starting at the root of the tree.

findall ( match )

Same asElement.findall(),starting at the root of the tree.

findtext ( match,default=None )

Same asElement.findtext(),starting at the root of the tree.

getiterator ( tag=None )

Deprecated since version 2.7:Use methodElementTree.iter()instead.

getroot ( )

Returns the root element for this tree.

iter ( tag=None )

Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree,in section order.tagis the tag to look for (default is to return all elements)

iterfind ( match )

New in version 2.7.

parse ( source,parser=None )

Loads an external XML section into this element tree.sourceis a file name or file object.parseris an optional parser instance. If not given,the standard XMLParser parser is used. Returns the section root element.

write ( file,xml_declaration=None,default_namespace=None,method="xml" )

Writes the element tree to a file,as XML.fileis a file name,or a file object opened for writing.encoding[1]is the output encoding (default is US-ASCII).xml_declarationcontrols if an XML declaration should be added to the file. Use False for never,True for always,None for only if not US-ASCII or UTF-8 (default is None).default_namespacesets the default XML namespace (for “xmlns”).methodis either"xml"). Returns an encoded string.

This is the XML file that is going to be manipulated:

<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>

Example of changing the attribute “target” of every link in first paragraph:

>>> from import ElementTree >>> tree = ElementTree() "index.xhtml") <Element 'html' at 0xb77e6fac> >>> p "body/p") # Finds first occurrence of tag p in body >>> p <Element 'p' at 0xb77ec26c> >>> links list(p"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" "output.xhtml")

19.7.3.4. QName Objects

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

QName wrapper. This can be used to wrap a QName attribute value,in order to get proper namespace handling on output.text_or_uriis a string containing the QName value,in the form {uri}local,or,if the tag argument is given,the URI part of a QName. Iftagis given,the first argument is interpreted as an URI,and this argument is interpreted as a local name.QNameinstances are opaque.

19.7.3.5. TreeBuilder Objects

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. Theelement_factoryis called to create newElementinstances when given.

close ( )

Flushes the builder buffers,and returns the toplevel document element. Returns anElementinstance.

data ( data )

Adds text to the current element.datais a string. This should be either a bytestring,or a Unicode string.

end ( tag )

Closes the current element.tagis the element name. Returns the closed element.

start ( tag,attrs )

Opens a new element.tagis the element name.attrsis a dictionary containing element attributes. Returns the opened element.

In addition,a customTreeBuilderobject can provide the following method:

doctype ( name,pubid,system )

Handles a doctype declaration.nameis the doctype name.pubidis the public identifier.systemis the system identifier. This method does not exist on the defaultTreeBuilderclass.

New in version 2.7.

19.7.3.6. XMLParser Objects

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

Elementstructure builder for XML source data,based on the expat parser.htmlare predefined HTML entities. This flag is not supported by the current implementation.targetis the target object. If omitted,the builder uses an instance of the standard TreeBuilder class.encoding[1]is optional. If given,the value overrides the encoding specified in the XML file.

close ( )

Finishes feeding data to the parser. Returns an element structure.

doctype ( name,system )

Deprecated since version 2.7:Define theTreeBuilder.doctype()method on a custom TreeBuilder target.

feed ( data )

Feeds data to the parser.datais encoded data.

XMLParser.feed()callstarget‘sstart()method for each opening tag,itsend()method for each closing tag,and data is processed by methoddata().XMLParser.close()callstarget‘s methodclose().XMLParsercan be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读