Python Read and write XML

Source: Internet
Author: User

python parsing of XML

The common XML programming interface has DOM and sax, and the two interfaces handle XML files in different ways, of course, using different scenarios.

Python has three ways to parse Xml:sax,dom, and ElementTree:

1.SAX (Simple API for XML)

The Python standard library contains the SAX parser, which uses the event-driven model to process XML files by triggering events and invoking user-defined callback functions during parsing of XML.

2.DOM (Document Object Model)

Parses XML data into a tree in memory, manipulating the XML by manipulating the tree.

3.ElementTree (element tree)

ElementTree is like a lightweight dom, with a convenient and friendly API. Good code availability, fast speed, low memory consumption.

Note: because the DOM needs to map XML data to a tree in memory, one is slower, the other is less memory, and Sax streams the XML file faster and consumes less memory, but requires the user to implement the callback function (handler).

The Xml.dom and Xml.sax packages define Python-bound DOM and sax interfaces.

The sub-modules of the XML package include:

    • Xml.etree.ElementTree:ElementTree API, lightweight XML processor
    • Xml.dom:DOM API
    • Xml.dom.minidom: the smallest DOM implementation
    • Xml.dom.pulldom: Supporting the construction of some dom trees
    • Xml.sax:SAX2 API
    • Xml.parsers.expat:Expat Resolver Bindings

xml.dom.minidom

You first need to parse the XML into the DOM, which is done through the parse method.

Parse (Filename_or_file, Parser=none, Bufsize=none)

Returns a Document object

Filename_or_file: File name or File object

Parse: Given must be a SAX2 parsing object

If your XML is written in a string, you can use the ParseString method

ParseString (String, Parser=none)

Python Read and write XML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.