Python-Ref > XML > DOM > XML DOM introduction
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

XML DOM introduction

What is a DOM?
Together with the XML the W3C has published the specification of DOM - the Document Object Model, level 1.
The DOM specification describes the API (APlication Interface) for accessing XML documents. Sofar this interface to XML was implemented in many languages and therefore its knowledge can be more-or-less directly used in many other programming languages.
The problem of this specification is that it is fairly minimalistic and especially the users of higher-level languages (such as JavaScript or Python) miss convenience functions for many common tasks. The other problem is that since the publication of the recommendation for Level 1 of DOM, two other levels (2 and 3) have been published.
In Python two major implementations of DOM exist. In many cases the two should be interchangable. The first one is called the minidom and is part of the standard Python disctribution package. The other, PyXML, is developed by a special interest group the XML SIG. It is a more complete implementation.
Both of the implementation mentioned above are compatible with DOM Level 1 and both have the namespace support from DOM Level 2.
The code below shows a simple example of working with DOM.
It is possible to get a DOM tree either from a string...
Expand/Shrink
Zdroj: (dom1-1.py)
  1   import xml.dom.minidom as dom  # this saves us some typing later
  2   
  3   xml_text = '<example number="1">This is an example XML text. <aaa>AAA</aaa></example>'
  4   
  5   doc = dom.parseString( xml_text)   # parse the string to get in-memory tree
  6   
  7   print doc
stdout:
<xml.dom.minidom.Document instance at 0x2aca9aeadab8>
Doba běhu: 71.3 ms
..or directly from a file.
Expand/Shrink
<examples>
  <example num="1">
    <title>Example 1</title>
    <text>This is example nr. 1. It shows how an example looks.</text>
  </example>

  <example num="2">
    <title>Example 2</title>
    <text>Another example. Imagine some ingenious text here...</text>
  </example>
</examples>
Zdroj: (dom1-2.py)
  1   import xml.dom.minidom as dom  # this saves us some typing later
  2   
  3   doc = dom.parse( "example.xml")   # parse a file to get in-memory tree
  4   
  5   print doc.toxml()
stdout:
<?xml version="1.0" ?>
<examples>
  <example num="1">
    <title>Example 1</title>
    <text>This is example nr. 1. It shows how an example looks.</text>
  </example>

  <example num="2">
    <title>Example 2</title>
    <text>Another example. Imagine some ingenious text here...</text>
  </example>
</examples>
Doba běhu: 57.8 ms
More useful examples are shown on the page Reading the DOM tree.