xmlutils.py :  » XML » pyRXP » pyRXP-1.13 » examples » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » XML » pyRXP 
pyRXP » pyRXP 1.13 » examples » xmlutils.py
"Some XML helper classes."
import os, string, sys
from types import StringType,ListType,TupleType
import pyRXP
assert pyRXP.version>='0.5', 'get the latest pyRXP!'
    

IGNOREWHITESPACE = 1

def ignoreWhitespace(list):
    newlist = []
    for elem in list:
        if type(elem) is StringType:
            short = string.strip(elem)
            if short == '':
                pass
            else:
                newlist.append(short)
        else:
            newlist.append(elem)
    return newlist


class TagWrapper:
    """Lazy utility for navigating XML.

    The following Python code works:

    tag.attribute      # returns given attribute
    tag.child          # returns first child with matching tag name
    for child in tag:  # iterates over them
    tag[3]             # returns fourth child
    len(tag)           # no of children
    """

    def __init__(self, node, returnEmptyTagContentAsString=1):
        tagName, attrs, children, spare = node
        self.tagName = tagName

        # this option affects tags with no content like <Surname></Surname>.
        # Can either return a None object, which is a pain in a prep file
        # as you have to  put if expressions around everything, or
        # an empty string so prep files can just do {{xml.wherever.Surname}}.
        self.returnEmptyTagContentAsString = returnEmptyTagContentAsString

        if attrs is None:
            self._attrs = {}
        else:
            self._attrs = attrs  # share the dictionary

        if children is None:
            self._children = []
        elif IGNOREWHITESPACE:
            self._children = ignoreWhitespace(children)
        else:
            self._children = children

    def __repr__(self):
        return 'TagWrapper<%s>' % self.tagName

    def __str__(self):
        if len(self):
            return str(self[0])
        else:
            if self.returnEmptyTagContentAsString:
                return ''
            else:
                return None

    def __len__(self):
        return len(self._children)

    def _value(self,name,default):
        try:
            return getattr(self,name)[0]
        except (AttributeError, IndexError):
            return default

    def __getattr__(self, attr):
        "Try various priorities"
        if self._attrs.has_key(attr):
            return self._attrs[attr]
        else:
            #first child tag whose name matches?
            for child in self._children:
                if type(child) is StringType:
                    pass
                else:
                    tagName, attrs, children, spare = child
                    if tagName == attr:
                        t = TagWrapper(child)
                        t.returnEmptyTagContentAsString = self.returnEmptyTagContentAsString
                        return t
            # not found, barf
            msg = '"%s" not found in attributes of tag <%s> or its children' % (attr, self.tagName)
            raise AttributeError, msg

    def keys(self):
        "return list of valid keys"
        result = self._attrs.keys()
        for child in self._children:
            if type(child) is StringType: pass
            else: result.append(child[0])
        return result

    def has_key(self,k):
        return k in self.keys()

    def __getitem__(self, idx):
        try:
            child = self._children[idx]
        except IndexError:
            raise IndexError, '%s no index %s' % (self.__repr__(), `idx`)
        if type(child) is StringType: return child
        else: return TagWrapper(child)

    def _namedChildren(self,name):
        R = []
        for c in self:
            if type(c) is StringType:
                if name is None: R.append(c)
            elif name == c.tagName: R.append(c)
        return R

def xml2doctree(xml):
    pyRXP_parse = pyRXP.Parser(
        ErrorOnValidityErrors=1,
        NoNoDTDWarning=1,
        ExpandCharacterEntities=0,
        ExpandGeneralEntities=0)
    return pyRXP_parse.parse(xml)


if __name__=='__main__':
    import os
    xml = open('rml_manual.xml','r').read()
    parsed = xml2doctree(xml)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.