Home > Store

XML Processing with Python

Register your product to gain access to bonus material or receive a coupon.

XML Processing with Python


  • Sorry, this book is no longer in print.
Not for Sale


  • Copyright 2000
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-021119-2
  • ISBN-13: 978-0-13-021119-4

  • Breakthrough techniques for building XML applications — fast!
  • Includes a detailed Python tutorial
  • Learn about DOM and SAX application development with Python
  • Exclusive coverage of the new Pyxie XML processing library
  • CD-ROM includes Python and Pyxie distributions for Windows NT and Linux—plus powerful utilities and lots of working code
"XML processing is the newest required skill for webmasters and application developers. The Python language and Sean McGrath's book make it fun to learn and easy to do."
— Charles F. Goldfarb

When it comes to XML processing, Python is in a league of its own.

If you're doing XML development without Python, you're wasting time! Python offers outstanding productivity — especially in the areas that matter most to XML developers, such as XML parsing, DOM/SAX implementations, string processing, and Internet APIs.

And now there's Pyxie — the new open source library that makes Python XML processing even easier and more powerful. In XML Processing with Python, top XML developer Sean McGrath delivers the hands-on explanations and examples you need to get results with Python and Pyxie fast — even if you've never used them before!

  • Install Python and the Pyxie XML package
  • Learn the fundamentals of Python: control structures, classes, nested lists, dictionaries, and regular rexpresions
  • Process XML with regular expression-driven, event-driven, and tree-driven techniques
  • Understand Python's support for DOM and SAX APIs
  • Explore the power of Python/XML through worked examples of GUI development, database integration, and an XML query-by-example implementation.

Elegant, easy, powerful and fun, Python helps you build world-class XML applications in less time than you ever imagined. If you know XML, one book has all the techniques, code, and tools you'll need to process it: XML Processing with Python.


The accompanying CD-ROM contains everything you need to develop XML applications with Python — including

  • complete Python distributions for Windows and Linux
  • the Pyxie open-source libraries
  • powerful utility programs
  • an extensive library of sample source code tested on both Windows NT and Linux

Sample Content

Online Sample Chapter

xMail: E-mail as XML

Downloadable Sample Chapter

Click here for a sample chapter for this book: 0130211192.pdf

Table of Contents

1. Introduction.

Purpose of This Book. The Pyxie Open Source Project. Prerequisites. How to Read This Book. A Note about Platforms. Structure of Code Samples. And Finally.

2. Installing Python.

Getting a Python Distribution. Installing the Software. Testing the Python Installation. Using a Python Program File. In Conclusion.

3. Installing the XML Package.

Testing the XML Package Installation. Testing the pyExpat Module. Testing SAX Support.

4. Tools of the Trade.

The xmln and xmlv Parsing Utilities. Simple XML-Processing Tasks with xmln and xmlv. The GetURL Utility-A Web Resource Retriever in Python. The PYX2XML Utility: Converting PYX to XML. The C3 Utility: An XML Document Editor/Viewer in Python. In Conclusion.

5. Just Enough Python.

Introduction. Basic Control Structures. Functions. Modules. Data Structures. Object Orientation. Design Principles. In Conclusion.

6. Some Important Details.

Dealing with Long Lines. Using the dir Function. Working with Docstrings. Importing Modules. Executing Python Programs. Using the Special Object None. Memory Management. Copying Objects. Determining Object Identity. Handling Errors. The Dynamic Nature of Python. Named Parameters. The Pass Statement. Packages.

7. Processing XML with Regular Expressions.

Command-Line Arguments. A Module Test Harness for xgrep. What If There Are No Command-Line Parameters? Adding Support for Wildcards. Parsing Command-Line Options. A Pattern-Matching Dry Run. Introducing Regular Expressions. Using Escape Sequences in Regular Expressions. Compiling Regular Expressions. Adding Regular Expressions to xgrep. xgrep in Action. Parsing XML with Regular Expressions. Cautionary Tales. Avoiding False Positive Matches. Shallow Parsing XML with Python Regular Expressions. Current Implementation of xgrep.

8. Event-driven XML Processing.

Making xgrep XML-Aware. Invoking xmln from xgrep. Adding PYX Support for xgrep. Adding XML Search Features to xgrep. Using Long Option Names in getopt. Using "Bit Twiddling" to Handle the Many Options Available. The Match Printing Function. Some Examples. Generalizing the Idea of Event-Based XML Processing. A Standardized Event-Driven Processing Model. Advantages and Disadvantages of Event-Driven Processing. In Conclusion.

9. Tree-driven XML Processing.

Modelling a Node. Navigating a Tree. Building xTree Structures. Building an xTree By Using PYX. A Test Harness for Pyxie. Handling Line Ends. A Syntax for Tree Processing with xgrep. Adding Support for Attributes. Some Utility Bits and Pieces. Implementing XMLGrepTree. A Standardized Tree-Driven XML Processing Model. Advantages and Disadvantages of Tree-Driven XML Processing. Some Examples. Bringing It All Together.

10. Just Enough SAX.

History. The Concept of an "Interface". Overview of the SAX Specification. The HandlerBase Class. The DocumentHandler Interface. The AttributeList Interface. The ErrorHandler Interface. A SAX Inspection Application. SAX as a Source of PYX. Switching SAX Parsers.

11. Just Enough DOM.

History. DOM Support in Python. The DOM Architecture. Accessing an XML File with pyDOM. Navigating a DOM Tree. Walking a DOM Tree. Accessing Attributes. Manipulating Trees. Accessing an HTML File with pyDOM. Printing the Text of an HTML Document. Changing Data Content in a DOM Tree. Creating a Tree Programmatically. Converting HTML to PYX by Using DOM. Using PYX as a DOM Data Source.

12. Pyxie: An Open Source XML- Processing Library for Python.

What Is Pyxie? Design Goals. PYX Notation Processing. Event-driven Processing. Tree-driven Processing. Tree Navigation. Tree Cut-and-Paste. Node Lists. Tree Walking. Hybrid Event- or Tree-driven Processing. The Invoice Printing Problem Solved Three Ways. The Complete Source Code for the Pyxie Library.

13. xFS: Filesystem Information in XML.

A Simple XML DTD for Filesystem Information. Some Python Features Used in the xFS Application. Viewing xFS Data with the C3 XML Editor/Viewer. Performing Filesystem Queries with xgrep. Source Code for xFS.

14. xMail: E-mail as XML.

The rfc822 Module. A Simple DTD for E-mail. An Example of an E-mail Message in XML. Processing a Eudora Mailbox. Processing a Linux Mailbox. Processing an E-mail Message by Using the rfc822 Module. Sending E-mail by Using xMail. Source Code for the SendxMail Application. Source Code for the xMail Application.

15. xMySQL: Relational Database Harvesting with Python SAX.

Installing MySQL. Testing the MySQL Installation. Installing the Python Interface to MySQL. Testing the Python Interface to MySQL. Mapping Relational Data to XML. The Python SAX Driver Interface. Implementing a SAX Driver for MySQL. A Template for SAX Drivers. The MySQL SAX Driver. Some Examples.

16. xTract: A Query-By-Example XML Retrieval System.

Expressing XML Queries. The xTract.py Utility in Action. xTract Version 1 Source Code. Handling Large XML Files with xTract. Source Code for the xTract1 Utility.

17. The C3 XML Editor/Viewer.

Developing wxPython Applications. A "Hello World" wxPython Application. Converting an xTree to a wxTree, and Vice Versa. Dynamic Module Loading. The Complete Source Code for C3.

Appendix A: An Overview of Python for Java Programmers.

Comparing the Python and Java Programming Languages.

Appendix B: An Overview of Python for Perl Programmers.




XML is everywhere on the Web these days. Structured data of all shapes and sizes such as financial transactions, news feeds, health care records, even HTML is metamorphosing into XML. There is just no getting away from it!

I'm glad actually. The fact that XML is everywhere is a fundamentally good thing in my opinion.

Why? Well, thanks to XML, the Web is in transition from an enormous repository of display-oriented, unstructured, low-level data (HTML) into a repository of structured, heterogenous, content-oriented information (XML). This new, improved World Wide Web, housed on a bedrock of XML, presents programmers with awesome opportunities for innovative software development.

This suits me just fine because software development is what I like to do--even more than writing books about software development.

The fact that the "L" in XML stands for "Language" has been the source of some confusion. It is important to remember that XML is a data representation technology. It is not, by any stretch of the imagination, a programming language. Its strength lies in its ability to simply and cleanly represent complex hierarchical data structures. As you know, XML is a World Wide Web Consortium (W3C) recommendation for structured data representation. There is no such thing as a W3C-recommended XML programming language. Choice of a programming tool is entirely within the hands of the individual developer. In making a selection, an embarrassment of riches presents itself to us. We have the Java programming language, Perl, Tcl, C++, C, JavaScript, Visual Basic, Delphi, and of course Python. Each language has its benefits and its drawbacks as an XML-processing tool.

How to choose?

Well, choosing a programming language is an inexact science at best and is influenced by many factors that are technical, commercial, emotional, futuristic and political in nature. Even serendipity has a role to play.

For my part, standing here (actually sitting here) at the start of the 21st century, I can safely say, without fear of contradiction, that no programming language I know comes close to Python for XML processing.

"Strong words," you may say, but then again, I am only speaking about the languages I know, not the ones I don't.

Enough said! We are not here to engage in programming language wars—that is what Usenet is for. Suffice it to say that Python is a solidly engineered, general-purpose programming language with a natural affinity for text processing in general and XML processing in particular. Mix XML and Python together and you have an explosive cocktail of information representation and information processing power.

In my opinion . . .

1.1 - Purpose of This Book

This book has essentially one purpose: To give you all the information, explanations, working examples, and software packages (on the accompanying CD-ROM) you need to start writing XML-processing applications in Python fast.

This book will not slow you down with intricate technical details of either Python or XML. That is not to say that these things are not important! They are very important, but they are not discussed in this book. The reason for this omission is that I believe a pragmatic treatment of a subject such as Python/XML is the best way to become productive quickly. I believe that comprehensive coverage of the details too early on in the exploration of a topic like this just gets in the way. So, in this book, comprehensive coverage takes second place to working examples of real-world Python/XML programming. I will provide plenty of pointers to more detailed information for those of you who wish to dig deeper.

1.2 - The Pyxie Open Source Project

This book heralds the beginning of the Pyxie project—an Open Source software development initiative aimed at fully developing Python's potential as an XML-processing platform.

By the time you read this, the Pyxie project will have been launched at http://www.pyxie.org. It contains all the source code from this book along with more demo programs and applications for Windows and Linux.

There is a mailing list for Pyxie. To subscribe, send e-mail to pyxie-request@starship.python.net with the word subscribe in the body of the e-mail.

Get involved!

1.3 - Prerequisites

This book assumes that you have a high-level understanding of the ideas and syntax of XML. In particular, it would be helpful if you know the following:

  • What an element is
  • What start-tags and end-tags look like
  • What the term "well formed XML" means
  • What a DTD (Document Type Definition) is for

If you feel the need to brush up your XML, you might like to read my book XML by Example: Building eCommerce Applications available in this series.

This book assumes that you have some previous programming experience in a high-level language. Some exposure to object-oriented programming is desirable but not critical. If you have any exposure at all to the Java programming language, Perl, awk, Tcl, C++, C, JavaScript, Visual Basic, Delphi, or shell scripting languages, you are in good shape to attack this book.

If your programming background is minimal, fear not! Python is a ridiculously easy programming language to learn. Indeed, it makes an excellent first programming language for those approaching the discipline afresh.

If you are a seasoned programmer in one or more languages, I believe you will be pleasantly surprised at how easy, natural, and (okay, I'll say it) beautiful Python is.

1.4 - How to Read This Book

This book is intended to be read from start to finish. One of the techniques I have used to avoid long tracts of narrative about Python language features or support libraries is that I explain them as they pop up in the course of writing real programs.

As a consequence, skipping material might lead to gaps in the presentation of Python features. Even if you are very familiar with the subject matter in a section of the book, please give it a high-level scan to ensure that you pick up on any Python nuggets buried inside.

If your background is Java, you might like to read Appendix A before continuing. It introduces Python from a Java programming language perspective. Similarly, you might like to read Appendix B at this point if your background is in the Perl programming language.

1.5 - A Note about Platforms

My day-to-day programming environment is a mixture of Windows NT 4.0 and Red Hat Linux 6.0. These are the two platforms that the software presented in this book has been developed and tested on.

Although the book focuses on Windows NT and Linux, the Python programs in the book and in the CD-ROM's root directory should run just fine on any Win32 or Unix platform. There will obviously be the usual assortment of differences to do with default installation directories, differing shells, and so on. I have not attempted to cover all the eventualities in this book. To do so would make it twice as long and ten times more tedious to read.

1.7 - And Finally ...

I am a programmer who learns best by example. If this is a reasonable description of how you learn best, you are in the right place.

If you have read this far, you will have surmised that this book is going to take a no-nonsense, snappy, and purposeful approach to XML processing with Python.

Ready? Let's go to work ...


Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020