Home  >  Article  >  Backend Development  >  python basic tutorial project three universal XML

python basic tutorial project three universal XML

不言
不言Original
2018-04-03 09:21:561679browse

This article mainly introduces the three universal XML of the python basic tutorial project in detail. It has certain reference value. Interested friends can refer to it.

The name of this project is not called universal. XML is better called automatically building a website. Based on an XML file, a website with a corresponding directory structure is generated. However, only HTML is still too simple. It would be more powerful if it could also generate CSS. This needs to be developed in the future. Let’s first study how to structure the HTML website. Since the website is generated through XML structure, everything should come from this XML file. Let’s first look at this XML file, website.xml:

<website>
 <page name="index" title="Home page">
 <h1>Welcome to my Home page</h1>
 <p>Hi, there. My name is Mr.gumby,and this is my home page,here are some of my int:</p>
 <ul>
  <li><a href="interests/shouting.html" rel="external nofollow" >Shouting</a></li>
  <li><a href="interests/sleeping.html" rel="external nofollow" >Sleeping</a></li>
  <li><a href="interests/eating.html" rel="external nofollow" >Eating</a></li>
 </ul>
 </page>
 <directory name="interests">
  <page name="shouting" title="Shouting">
   <h1>shouting page</h1>
   <p>....</p>
  </page>
  <page name="sleeping" title="Sleeping">
   <h1>sleeping page</h1>
   <p>...</p>
  </page>
  <page name="eating" title="Eating">
    <h1>Eating page</h1>
    <p>....</p>
  </page>
 </directory>
</website>

With this file, let’s look at how to generate a website through this file.

First we have to parse this xml file. Python parses xml the same as in java. There are two ways, SAX and DOM. The difference between the two processing methods is speed and scope. The former focuses on Efficiency, only processing a small part of the document at a time, using memory quickly and effectively. The latter is the opposite processing method, loading all documents into the memory first, and then processing, which is slower and more consuming. The only advantage of memory is that it can operate the entire document.

To use sax to process xml in python, you must first introduce the parse function in xml.sax and the ContentHandler in xml.sax.handler. The latter class must cooperate with the parse function. in use. The usage is as follows: parse('xxx.xml',xxxHandler), the xxxHandler here needs to inherit the ContentHandler above, but just inherit it, no need to do anything. Then when the parse function processes the xml file, it will call the startElement function and endElement function in xxxHandler to start and end the tag in xml. The middle process uses a function named characters to process all the strings inside the tag. .

With the above understanding, we already know how to process xml files, and then look at the website.xml file, the source of evil, and analyze its structure. There are only two nodes: page and directory. Obviously page represents a page and directory represents a directory.

So the idea of ​​processing this xml file becomes clear. Read each node of the xml file, then determine whether it is a page or a directory. If it is a page, create an html page, and then write the contents of the node to the file. If directory is encountered, create a folder and then process the page node inside it (if it exists).
Let’s look at this part of the code. The implementation in the book is more complex and flexible. Let’s look at it first, then analyze it.

from xml.sax.handler import ContentHandler
from xml.sax import parse
import os
class Dispatcher:
    def dispatch(self, prefix, name, attrs=None):
        mname = prefix + name.capitalize()
        dname = &#39;default&#39; + prefix.capitalize()
        method = getattr(self, mname, None)
        if callable(method): args = ()
        else:
            method = getattr(self, dname, None)
            args = name,
        if prefix == &#39;start&#39;: args += attrs,
        if callable(method): method(*args)
    def startElement(self, name, attrs):
        self.dispatch(&#39;start&#39;, name, attrs)
    def endElement(self, name):
        self.dispatch(&#39;end&#39;, name)
class WebsiteConstructor(Dispatcher, ContentHandler):
    passthrough = False
    def __init__(self, directory):
        self.directory = [directory]
        self.ensureDirectory()
    def ensureDirectory(self):
        path = os.path.join(*self.directory)
        print path
        print &#39;----&#39;
        if not os.path.isdir(path): os.makedirs(path)
    def characters(self, chars):
        if self.passthrough: self.out.write(chars)
    def defaultStart(self, name, attrs):
        if self.passthrough:
            self.out.write(&#39;<&#39; + name)
            for key, val in attrs.items():
                self.out.write(&#39; %s="%s"&#39; %(key, val))
            self.out.write(&#39;>&#39;)
    def defaultEnd(self, name):
        if self.passthrough:
            self.out.write(&#39;</%s>&#39; % name)
    def startDirectory(self, attrs):
        self.directory.append(attrs[&#39;name&#39;])
        self.ensureDirectory()
    def endDirectory(self):
        print &#39;endDirectory&#39;
        self.directory.pop()
    def startPage(self, attrs):
        print &#39;startPage&#39;
        filename = os.path.join(*self.directory + [attrs[&#39;name&#39;]+&#39;.html&#39;])
        self.out = open(filename, &#39;w&#39;)
        self.writeHeader(attrs[&#39;title&#39;])
        self.passthrough = True
    def endPage(self):
        print &#39;endPage&#39;
        self.passthrough = False
        self.writeFooter()
        self.out.close()
    def writeHeader(self, title):
        self.out.write(&#39;<html>\n <head>\n  <title>&#39;)
        self.out.write(title)
        self.out.write(&#39;</title>\n </head>\n <body>\n&#39;)
    def writeFooter(self):
        self.out.write(&#39;\n </body>\n</html>\n&#39;)
parse(&#39;website.xml&#39;,WebsiteConstructor(&#39;public_html&#39;))

It seems that the above analysis of this program is a bit more complicated, but the great man Maomao said that any complex program is a paper tiger. Then let's analyze this program again.

First of all, I saw that this program has two classes. In fact, it can be regarded as one class because of inheritance.

Then let’s look at what else it has. In addition to the startElement, endElement and characters we analyzed, there are also startPage, endPage; startDirectory, endDirectory; defaultStart, defaultEnd; ensureDirectory; writeHeader, writeFooter; and dispatch, these functions. Except for dispatch, the previous functions are easy to understand. Each pair of functions simply processes the corresponding html tags and xml nodes. Dispatch is more complicated. The complexity is that it is used to dynamically combine functions and execute them.

The processing idea of ​​dispatch is to first determine whether there is a corresponding function such as startPage based on the passed parameters (that is, the operation name and node name). If it does not exist, execute default+operation name: such as defaultStart.

After you understand each function one by one, you will know what the entire processing flow is like. First create a public_html file to store the entire website, then read the xml nodes, and call dispatch through startElement and endElement for processing. Then there is how dispatch calls the specific processing function. At this point, the analysis of this project has been completed.

The main content to master is the use of SAX to process XML in python, and the other is the use of functions in python, such as getattr, asterisks when passing parameters...

Related Recommended:

Python Basic Tutorial Project 2: Good Pictures

Python Basic Tutorial Project 4: News Aggregation

The above is the detailed content of python basic tutorial project three universal XML. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn