diff --git a/pisi/pxml/xmlext.py b/pisi/pxml/xmlext.py index 654ca717..9189f40d 100644 --- a/pisi/pxml/xmlext.py +++ b/pisi/pxml/xmlext.py @@ -10,14 +10,158 @@ # Please read the COPYING file. # -try: - from xmlextpiks import * -except: - try: - #if pisi.context.use_mdom: - # gibidi - from xmlextcdom import * - except: - #raise Error('cannot find 4suite implementation') - print 'xmlext: piksemel or cDomlette implementation cannot be loaded, falling back to minidom' - from xmlextmdom import * +""" + xmlext is a helper module for accessing XML files using + xml.dom.minidom . It is a convenient wrapper for some + DOM functions, and provides path based get/add functions + as in KDE API. + + function names are mixedCase for compatibility with minidom, + an 'old library' + + this implementation uses piksemel +""" + +import gettext +__trans = gettext.translation('pisi', fallback=True) +_ = __trans.ugettext + +import pisi +import piksemel as iks + +parse = iks.parse +newDocument = iks.newDocument + +def getAllNodes(node, tagPath): + """retrieve all nodes that match a given tag path.""" + tags = tagPath.split('/') + if len(tags) == 0: + return [] + nodeList = [node] # basis case + for tag in tags: + results = map(lambda x: getTagByName(x, tag), nodeList) + nodeList = [] + for x in results: + nodeList.extend(x) + pass # emacs indentation error, keep it here + if len(nodeList) == 0: + return [] + return nodeList + +def getNodeAttribute(node, attrname): + """get named attribute from DOM node""" + return node.getAttribute(attrname) + +def setNodeAttribute(node, attrname, value): + """get named attribute from DOM node""" + return node.setAttribute(attrname, value) + +def getChildElts(parent): + """get only child elements""" + return [x for x in parent.tags()] + +def getTagByName(parent, childName): + return [x for x in parent.tags(childName)] + +def getNodeText(node, tagpath = ""): + """get the first child and expect it to be text!""" + if tagpath!="": + node = getNode(node, tagpath) + if not node: + return None + child = node.firstChild() + if not child: + return None + if child.type() == iks.DATA: + # in any case, strip whitespaces... + return child.data().strip() + else: + raise XmlError(_("getNodeText: Expected text node, got something else!")) + +def getChildText(node_s, tagpath): + """get the text of a child at the end of a tag path""" + node = getNode(node_s, tagpath) + if not node: + return None + return getNodeText(node) + +def getNode(node, tagpath): + """returns the *first* matching node for given tag path.""" + + if tagpath == "": + return node + + assert type(tagpath)==str + tags = tagpath.split('/') + assert len(tags)>0 + + # iterative code to search for the path + for tag in tags: + currentNode = None + for child in node.tags(): + if child.name() == tag: + currentNode = child + break + if not currentNode: + return None + else: + node = currentNode + return currentNode + +def createTagPath(node, tags): + """create new child at the end of a tag chain starting from node + no matter what""" + if len(tags)==0: + return node + for tag in tags: + node = node.insertTag(tag) + return node + +def addTagPath(node, tags, newnode=None): + """add newnode at the end of a tag chain, smart one""" + node = createTagPath(node, tags) + if newnode: # node to add specified + node.insertNode(newnode) + return node + +def addNode(node, tagpath, newnode = None, branch=True): + """add a new node at the end of the tree and returns it + if newnode is given adds that node, too.""" + + assert type(tagpath)==str + tags = [] + if tagpath != "": + tags = tagpath.split('/') # tag chain + else: + addTagPath(node, [], newnode) + return node #FIXME: is this correct!?!? + + assert len(tags)>0 # we want a chain + + # iterative code to search for the path + + if branch: + rem = 1 + else: + rem = 0 + + while len(tags) > rem: + tag = tags.pop(0) + nodeList = getTagByName(node, tag) + if len(nodeList) == 0: # couldn't find + tags.insert(0, tag) # put it back in + return addTagPath(node, tags, newnode) + else: + node = nodeList[len(nodeList)-1] # discard other matches + else: + # had only one tag.. + return addTagPath(node, tags, newnode) + + return node + +def addText(node, tagpath, text): + node = addNode(node, tagpath) + node.insertData(text) + +def newNode(node, tag): + return iks.newDocument(tag) diff --git a/pisi/pxml/xmlextcdom.py b/pisi/pxml/xmlextcdom.py deleted file mode 100644 index 302f8d1b..00000000 --- a/pisi/pxml/xmlextcdom.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - xmlext is a helper module for accessing XML files using - xml.dom.minidom . It is a convenient wrapper for some - DOM functions, and provides path based get/add functions - as in KDE API. - - function names are mixedCase for compatibility with minidom, - an 'old library' - - this implementation uses cDomlette from 4suite.org - adapted from the minidom implementation by Faik Uygur and fixed by Eray -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import Ft -from Ft.Xml.Domlette import implementation -from Ft.Xml.Domlette import NoExtDtdReader -import Ft.Lib -import pisi - -from xml.dom import XHTML_NAMESPACE, XML_NAMESPACE -XHTML_NS = unicode(XHTML_NAMESPACE) -XML_NS = unicode(XML_NAMESPACE) - -class XmlError(pisi.Error): - "named this way because the class if mostly used with an import *" - pass - -# Document wrappers - -def newDocument(tag): - # create a document and return document root - doc = implementation.createDocument(None, tag, None) - return doc.documentElement - -def parse(filename): - # parse file and return document root - try: - doc = NoExtDtdReader.parseUri(Ft.Lib.Uri.OsPathToUri(filename)) - return doc.documentElement - except Ft.FtException, e: - raise Error(_("File '%s' has invalid XML: %s") % (filename, str(e))) - -def newNode(node, tag): - return node.ownerDocument.createElementNS(None, tag) - -def newTextNode(node, text): - return node.ownerDocument.createTextNode(text) - -# Node related wrappers - -def getNodeAttribute(node, attrname): - """get named attribute from DOM node""" - if attrname.startswith('xml:'): - if node.hasAttributeNS(XML_NS, attrname[4:]): - return node.getAttributeNS(XML_NS, attrname[4:]) - else: - return None - else: - if not node.hasAttributeNS(None, attrname): - return None - else: - return node.getAttributeNS(None, attrname) - -def setNodeAttribute(node, attrname, value): - """get named attribute from DOM node""" - if attrname.startswith('xml:'): - node.setAttributeNS(XML_NS, attrname, value) - else: - node.setAttributeNS(None, attrname, value) - -def getChildElts(node): - """get only child elements""" - return filter(lambda x:x.nodeType == x.ELEMENT_NODE, node.childNodes) - -def getTagByName(parent, childName): - return [x for x in parent.childNodes - if x.nodeType == x.ELEMENT_NODE and x.tagName == childName] - -def getNodeText(node, tagpath = ""): - """get the first child and expect it to be text!""" - if tagpath!="": - node = getNode(node, tagpath) - try: - child = node.childNodes[0] - except IndexError: - return None - except AttributeError: # no node by that name - return None - if child.nodeType == child.TEXT_NODE: - # in any case, strip whitespaces... - return child.data.strip() - else: - raise XmlError(_("getNodeText: Expected text node, got something else!")) - -def getChildText(node_s, tagpath): - """get the text of a child at the end of a tag path""" - node = getNode(node_s, tagpath) - if not node: - return None - return getNodeText(node) - -def getNode(node, tagpath): - """returns the *first* matching node for given tag path.""" - - assert type(tagpath)==str - tags = tagpath.split('/') - assert len(tags)>0 - - # iterative code to search for the path - for tag in tags: - currentNode = None - for child in node.childNodes: - if child.nodeType == node.ELEMENT_NODE and child.tagName == tag: - currentNode = child - break - if not currentNode: - return None - else: - node = currentNode - return currentNode - -def getAllNodes(node, tagPath): - """retrieve all nodes that match a given tag path.""" - - tags = tagPath.split('/') - - if len(tags) == 0: - return [] - - nodeList = [node] # basis case - - for tag in tags: - results = map(lambda x: getTagByName(x, tag), nodeList) - nodeList = [] - for x in results: - nodeList.extend(x) - pass # emacs indentation error, keep it here - - if len(nodeList) == 0: - return [] - - return nodeList - -def createTagPath(node, tags): - """create new child at the end of a tag chain starting from node - no matter what""" - if len(tags)==0: - return node - dom = node.ownerDocument - for tag in tags: - node = node.appendChild(dom.createElementNS(None, tag)) - return node - -def addTagPath(node, tags, newnode=None): - """add newnode at the end of a tag chain, smart one""" - node = createTagPath(node, tags) - if newnode: # node to add specified - node.appendChild(newnode) - return node - -def addNode(node, tagpath, newnode = None, branch=True): - """add a new node at the end of the tree and returns it - if newnode is given adds that node, too.""" - - assert type(tagpath)==str - tags = [] - if tagpath != "": - tags = tagpath.split('/') # tag chain - else: - addTagPath(node, [], newnode) - return node #FIXME: is this correct!?!? - - assert len(tags)>0 # we want a chain - - # iterative code to search for the path - - if branch: - rem = 1 - else: - rem = 0 - - while len(tags) > rem: - tag = tags.pop(0) - nodeList = getTagByName(node, tag) - if len(nodeList) == 0: # couldn't find - tags.insert(0, tag) # put it back in - return addTagPath(node, tags, newnode) - else: - node = nodeList[len(nodeList)-1] # discard other matches - else: - # had only one tag.. - return addTagPath(node, tags, newnode) - - return node - -def addText(node, tagPath, text, branch = True): - newnode = newTextNode(node, text) - return addNode(node, tagPath, newnode, branch = branch) diff --git a/pisi/pxml/xmlextmdom.py b/pisi/pxml/xmlextmdom.py deleted file mode 100644 index 66ab741e..00000000 --- a/pisi/pxml/xmlextmdom.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - xmlext is a helper module for accessing XML files using - xml.dom.minidom . It is a convenient wrapper for some - DOM functions, and provides path based get/add functions - as in KDE API. - - function names are mixedCase for compatibility with minidom, - an 'old library' - - note: this is a particularly inefficient implementation of xmlext. -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import xml.dom.minidom as mdom -from xml.parsers.expat import ExpatError - -import pisi - -class XmlError(pisi.Error): - "named this way because the class if mostly used with an import *" - pass - -# Document wrappers - -def newDocument(tag): - impl = mdom.getDOMImplementation() - dom = impl.createDocument(None, tag, None) - return dom.documentElement - -def parse(filename): - try: - dom = mdom.parse(filename) - return dom.documentElement - except ExpatError, inst: - raise Error(_("File '%s' has invalid XML: %s\n") % (fileName, - str(inst))) - -def newNode(node, tag): - return node.ownerDocument.createElement(tag) - -def newTextNode(node, text): - return node.ownerDocument.createTextNode(text) - -# Node related wrappers - -def getNodeAttribute(node, attrname): - """get named attribute from DOM node""" - if not node.hasAttribute(attrname): - return None - return node.getAttribute(attrname) - -def getChildElts(node): - """get only child elements""" - return filter(lambda x:x.nodeType == x.ELEMENT_NODE, node.childNodes) - -def getTagByName(parent, childName): - return [x for x in parent.childNodes - if x.nodeType == x.ELEMENT_NODE and x.tagName == childName] - -def getNodeText(node, tagpath = ""): - """get the first child and expect it to be text!""" - if tagpath!="": - node = getNode(node, tagpath) - try: - child = node.childNodes[0] - except IndexError: - return None - except AttributeError: # no node by that name - return None - if child.nodeType == child.TEXT_NODE: - # in any case, strip whitespaces... - return child.data.strip() - else: - raise XmlError(_("getNodeText: Expected text node, got something else!")) - -def getChildText(node_s, tagpath): - """get the text of a child at the end of a tag path""" - node = getNode(node_s, tagpath) - if not node: - return None - return getNodeText(node) - -def getNode(node, tagpath): - """returns the *first* matching node for given tag path.""" - - assert type(tagpath)==str - tags = tagpath.split('/') - assert len(tags)>0 - - # iterative code to search for the path - for tag in tags: - currentNode = None - for child in node.childNodes: - if child.nodeType == node.ELEMENT_NODE and child.tagName == tag: - currentNode = child - break - if not currentNode: - return None - else: - node = currentNode - return currentNode - -def getAllNodes(node, tagPath): - """retrieve all nodes that match a given tag path.""" - - tags = tagPath.split('/') - - if len(tags) == 0: - return [] - - nodeList = [node] # basis case - - for tag in tags: - results = map(lambda x: getTagByName(x, tag), nodeList) - nodeList = [] - for x in results: - nodeList.extend(x) - pass # emacs indentation error, keep it here - - if len(nodeList) == 0: - return [] - - return nodeList - -def createTagPath(node, tags): - """create new child at the end of a tag chain starting from node - no matter what""" - if len(tags)==0: - return node - dom = node.ownerDocument - for tag in tags: - node = node.appendChild(dom.createElement(tag)) - return node - -def addTagPath(node, tags, newnode=None): - """add newnode at the end of a tag chain, smart one""" - node = createTagPath(node, tags) - if newnode: # node to add specified - node.appendChild(newnode) - return node - -def addNode(node, tagpath, newnode = None, branch=True): - """add a new node at the end of the tree and returns it - if newnode is given adds that node, too.""" - - assert type(tagpath)==str - tags = [] - if tagpath != "": - tags = tagpath.split('/') # tag chain - else: - addTagPath(node, [], newnode) - return node #FIXME: is this correct!?!? - - assert len(tags)>0 # we want a chain - - # iterative code to search for the path - - if branch: - rem = 1 - else: - rem = 0 - - while len(tags) > rem: - tag = tags.pop(0) - nodeList = getTagByName(node, tag) - if len(nodeList) == 0: # couldn't find - tags.insert(0, tag) # put it back in - return addTagPath(node, tags, newnode) - else: - node = nodeList[len(nodeList)-1] # discard other matches - else: - # had only one tag.. - return addTagPath(node, tags, newnode) - - return node - -def addText(node, tagPath, text, branch = True): - newnode = newTextNode(node, text) - return addNode(node, tagPath, newnode, branch = branch) diff --git a/pisi/pxml/xmlextpiks.py b/pisi/pxml/xmlextpiks.py deleted file mode 100644 index 9189f40d..00000000 --- a/pisi/pxml/xmlextpiks.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - xmlext is a helper module for accessing XML files using - xml.dom.minidom . It is a convenient wrapper for some - DOM functions, and provides path based get/add functions - as in KDE API. - - function names are mixedCase for compatibility with minidom, - an 'old library' - - this implementation uses piksemel -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import pisi -import piksemel as iks - -parse = iks.parse -newDocument = iks.newDocument - -def getAllNodes(node, tagPath): - """retrieve all nodes that match a given tag path.""" - tags = tagPath.split('/') - if len(tags) == 0: - return [] - nodeList = [node] # basis case - for tag in tags: - results = map(lambda x: getTagByName(x, tag), nodeList) - nodeList = [] - for x in results: - nodeList.extend(x) - pass # emacs indentation error, keep it here - if len(nodeList) == 0: - return [] - return nodeList - -def getNodeAttribute(node, attrname): - """get named attribute from DOM node""" - return node.getAttribute(attrname) - -def setNodeAttribute(node, attrname, value): - """get named attribute from DOM node""" - return node.setAttribute(attrname, value) - -def getChildElts(parent): - """get only child elements""" - return [x for x in parent.tags()] - -def getTagByName(parent, childName): - return [x for x in parent.tags(childName)] - -def getNodeText(node, tagpath = ""): - """get the first child and expect it to be text!""" - if tagpath!="": - node = getNode(node, tagpath) - if not node: - return None - child = node.firstChild() - if not child: - return None - if child.type() == iks.DATA: - # in any case, strip whitespaces... - return child.data().strip() - else: - raise XmlError(_("getNodeText: Expected text node, got something else!")) - -def getChildText(node_s, tagpath): - """get the text of a child at the end of a tag path""" - node = getNode(node_s, tagpath) - if not node: - return None - return getNodeText(node) - -def getNode(node, tagpath): - """returns the *first* matching node for given tag path.""" - - if tagpath == "": - return node - - assert type(tagpath)==str - tags = tagpath.split('/') - assert len(tags)>0 - - # iterative code to search for the path - for tag in tags: - currentNode = None - for child in node.tags(): - if child.name() == tag: - currentNode = child - break - if not currentNode: - return None - else: - node = currentNode - return currentNode - -def createTagPath(node, tags): - """create new child at the end of a tag chain starting from node - no matter what""" - if len(tags)==0: - return node - for tag in tags: - node = node.insertTag(tag) - return node - -def addTagPath(node, tags, newnode=None): - """add newnode at the end of a tag chain, smart one""" - node = createTagPath(node, tags) - if newnode: # node to add specified - node.insertNode(newnode) - return node - -def addNode(node, tagpath, newnode = None, branch=True): - """add a new node at the end of the tree and returns it - if newnode is given adds that node, too.""" - - assert type(tagpath)==str - tags = [] - if tagpath != "": - tags = tagpath.split('/') # tag chain - else: - addTagPath(node, [], newnode) - return node #FIXME: is this correct!?!? - - assert len(tags)>0 # we want a chain - - # iterative code to search for the path - - if branch: - rem = 1 - else: - rem = 0 - - while len(tags) > rem: - tag = tags.pop(0) - nodeList = getTagByName(node, tag) - if len(nodeList) == 0: # couldn't find - tags.insert(0, tag) # put it back in - return addTagPath(node, tags, newnode) - else: - node = nodeList[len(nodeList)-1] # discard other matches - else: - # had only one tag.. - return addTagPath(node, tags, newnode) - - return node - -def addText(node, tagpath, text): - node = addNode(node, tagpath) - node.insertData(text) - -def newNode(node, tag): - return iks.newDocument(tag) diff --git a/pisi/pxml/xmlfile.py b/pisi/pxml/xmlfile.py index e4f91a91..15355940 100644 --- a/pisi/pxml/xmlfile.py +++ b/pisi/pxml/xmlfile.py @@ -10,13 +10,78 @@ # Please read the COPYING file. # -import pisi.context +""" + XmlFile class further abstracts a dom object using the + high-level dom functions provided in xmlext module (and sorely lacking + in xml.dom :( ) -try: - from xmlfilepiks import * -except: - try: - from xmlfilecdom import * - except: - print 'xmlext: cDomlette/piksemel implementation cannot be loaded, falling back to minidom' - from xmlfilemdom import * + function names are mixedCase for compatibility with minidom, + an 'old library' + + this implementation uses piksemel +""" + +import gettext +__trans = gettext.translation('pisi', fallback=True) +_ = __trans.ugettext + +import codecs +import exceptions + +import piksemel as iks + +import pisi +from pisi.file import File +from pisi.util import join_path as join + +class Error(pisi.Error): + pass + +class XmlFile(object): + """A class to help reading and writing an XML file""" + + def __init__(self, tag): + self.rootTag = tag + + def newDocument(self): + """clear DOM""" + self.doc = iks.newDocument(self.rootTag) + + def unlink(self): + """deallocate DOM structure""" + del self.doc + + def rootNode(self): + """returns root document element""" + return self.doc + + def readxmlfile(self, file): + raise Exception("not implemented") + try: + self.doc = iks.parse(file) + return self.doc + except Exception, e: + raise Error(_("File '%s' has invalid XML") % (localpath) ) + + + def readxml(self, uri, tmpDir='/tmp', sha1sum=False, + compress=None, sign=None, copylocal = False): + uri = File.make_uri(uri) + #try: + localpath = File.download(uri, tmpDir, sha1sum=sha1sum, + compress=compress,sign=sign, copylocal=copylocal) + #except IOError, e: + # raise Error(_("Cannot read URI %s: %s") % (uri, unicode(e)) ) + try: + self.doc = iks.parse(localpath) + return self.doc + except Exception, e: + raise Error(_("File '%s' has invalid XML") % (localpath) ) + + def writexml(self, uri, tmpDir = '/tmp', sha1sum=False, compress=None, sign=None): + f = File(uri, File.write, sha1sum=sha1sum, compress=compress, sign=sign) + f.write(self.doc.toPrettyString()) + f.close() + + def writexmlfile(self, f): + f.write(self.doc.toPrettyString()) diff --git a/pisi/pxml/xmlfilecdom.py b/pisi/pxml/xmlfilecdom.py deleted file mode 100644 index d92d46e6..00000000 --- a/pisi/pxml/xmlfilecdom.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - XmlFile class further abstracts a dom object using the - high-level dom functions provided in xmlext module (and sorely lacking - in xml.dom :( ) - - function names are mixedCase for compatibility with minidom, - an 'old library' - - this implementation uses cDomlette from 4suite.org - adapted from the minidom implementation by Faik Uygur and fixed by Eray -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import codecs -import exceptions - -import Ft -from Ft.Xml.Domlette import implementation -from Ft.Xml.Domlette import NoExtDtdReader -from Ft.Xml.Domlette import Print, PrettyPrint -from xml.dom import XHTML_NAMESPACE, XML_NAMESPACE - -XHTML_NS = unicode(XHTML_NAMESPACE) -XML_NS = unicode(XML_NAMESPACE) - -import pisi -from pisi.pxml.xmlextcdom import * -from pisi.file import File -from pisi.util import join_path as join - -class Error(pisi.Error): - pass - -class XmlFile(object): - """A class to help reading and writing an XML file""" - - def __init__(self, tag): - self.rootTag = tag - - def newDocument(self): - """clear DOM""" - self.doc = implementation.createDocument(None, self.rootTag, None) - - def unlink(self): - """deallocate DOM structure""" - del self.doc - - def rootNode(self): - """returns root document element""" - return self.doc.documentElement - - def readxml(self, uri, tmpDir='/tmp', sha1sum=False, compress=None, sign=None): - uri = File.make_uri(uri) - localpath = File.download(uri, tmpDir,sha1sum=sha1sum,compress=compress,sign=sign) - try: - self.doc = NoExtDtdReader.parseUri(Ft.Lib.Uri.OsPathToUri(localpath)) - return self.doc.documentElement - except Ft.FtException, e: - raise Error(_("File '%s' has invalid XML: %s") % (localpath, str(e)) ) - except exceptions.ValueError, e: - raise Error(_("File '%s' not found") % localpath ) - - def writexml(self, uri, tmpDir = '/tmp', sha1sum=False, compress=None, sign=None): - f = File(uri, File.write, sha1sum=sha1sum, compress=compress, sign=sign) - PrettyPrint(self.rootNode(), stream = f) - f.close() - - def verifyRootTag(self): - actual_roottag = self.rootNode().tagName - if actual_roottag != self.rootTag: - raise Error(_("Root tagname %s not identical to %s as expected") % - (actual_roottag, self.rootTag) ) - - # construction helpers - - def newNode(self, tag): - return self.doc.createElementNS(None, tag) - - def newTextNode(self, text): - return self.doc.createTextNode(text) - - def newAttribute(self, attr): - return self.doc.createAttribute(attr) - - # read helpers - - def getNode(self, tagPath = ""): - """returns the *first* matching node for given tag path.""" - self.verifyRootTag() - return getNode(self.doc.documentElement, tagPath) - - def getNodeText(self, tagPath): - """returns the text of *first* matching node for given tag path.""" - node = self.getNode(tagPath) - if not node: - return None - return getNodeText(node) - - def getAllNodes(self, tagPath): - """returns all nodes matching a given tag path.""" - self.verifyRootTag() - return getAllNodes(self.doc.documentElement, tagPath) - - def getChildren(self, tagpath): - """ returns the children of the given path""" - node = self.getNode(tagpath) - return node.childNodes - - # get only elements of a given type - #FIXME: this doesn't work - def getChildrenWithType(self, tagpath, type): - """ returns the children of the given path, only with given type """ - node = self.getNode(tagpath) - return filter(lambda x:x.nodeType == type, node.childNodes) - - # get only child elements - def getChildElts(self, tagpath): - """ returns the children of the given path, only with given type """ - node = self.getNode(tagpath) - try: - return filter(lambda x:x.nodeType == x.ELEMENT_NODE, - node.childNodes) - except AttributeError: - return None - - # write helpers - - def addNode(self, tagPath, newnode = None): - "this adds the newnode under given tag path" - self.verifyRootTag() - return addNode(self.doc.documentElement, tagPath, newnode) - - def addNodeUnder(self, node, tagPath, newnode = None): - "this adds the new stuff under node and then following tag path" - self.verifyRootTag() - return addNode(node, tagPath, newnode) - - def addChild(self, newnode): - "add a new child node right under root element document" - self.doc.documentElement.appendChild(newnode) - - def addText(self, node, text): - "add text to node" - node.appendChild(self.newTextNode(text)) - - def addTextNode(self, tagPath, text): - "add a text node with given tag path" - node = self.addNode(tagPath, self.newTextNode(text)) - return node - - def addTextNodeUnder(self, node, tagPath, text): - "add a text node under given node with tag path (phew)" - return self.addNodeUnder(node, tagPath, self.newTextNode(text)) diff --git a/pisi/pxml/xmlfilemdom.py b/pisi/pxml/xmlfilemdom.py deleted file mode 100644 index 44c2e0ca..00000000 --- a/pisi/pxml/xmlfilemdom.py +++ /dev/null @@ -1,159 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - XmlFile class further abstracts a dom object using the - high-level dom functions provided in xmlext module (and sorely lacking - in xml.dom :( ) - - function names are mixedCase for compatibility with minidom, - an 'old library' - - note: this is a particularly inefficient implementation of xmlfile -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import xml.dom.minidom as mdom -from xml.parsers.expat import ExpatError -import codecs - -import pisi -from pisi.file import File - -class Error(pisi.Error): - "named this way because the class if mostly used with an import *" - pass - -class XmlFile(object): - """A class to help reading and writing an XML file""" - - def __init__(self, tag): - self.rootTag = tag - - def newDocument(self): - """clear DOM""" - impl = mdom.getDOMImplementation() - self.doc = impl.createDocument(None, self.rootTag, None) - - def unlink(self): - """deallocate DOM structure""" - self.doc.unlink() - del self.doc - - def rootNode(self): - """returns root document element""" - return self.doc.documentElement - - def readxml(self, uri, tmpDir = '/tmp'): - uri = File.make_uri(uri) - localpath = File.download(uri, tmpDir) - - try: - self.doc = mdom.parse(localpath) - except ExpatError, inst: - raise Error(_("File '%s' has invalid XML: %s\n") % (fileName, - str(inst))) - - def writexml(self, fileName): - f = codecs.open(fileName,'w', "utf-8") - f.write(self.doc.toprettyxml()) - f.close() - - def verifyRootTag(self): - actual_roottag = self.rootNode().tagName - if actual_roottag != self.rootTag: - raise Error(_("Root tagname %s not identical to %s as expected") % - (actual_roottag, self.rootTag) ) - - # construction helpers - - def newNode(self, tag): - return self.doc.createElement(tag) - - def newTextNode(self, text): - return self.doc.createTextNode(text) - - def newAttribute(self, attr): - return self.doc.createAttribute(attr) - - # read helpers - - def getNode(self, tagPath = ""): - """returns the *first* matching node for given tag path.""" - self.verifyRootTag() - return getNode(self.doc.documentElement, tagPath) - - def getNodeText(self, tagPath): - """returns the text of *first* matching node for given tag path.""" - node = self.getNode(tagPath) - if not node: - return None - return getNodeText(node) - - def getAllNodes(self, tagPath): - """returns all nodes matching a given tag path.""" - self.verifyRootTag() - return getAllNodes(self.doc.documentElement, tagPath) - - def getChildren(self, tagpath): - """ returns the children of the given path""" - node = self.getNode(tagpath) - return node.childNodes - - # get only elements of a given type - #FIXME: this doesn't work - def getChildrenWithType(self, tagpath, type): - """ returns the children of the given path, only with given type """ - node = self.getNode(tagpath) - return filter(lambda x:x.nodeType == type, node.childNodes) - - # get only child elements - def getChildElts(self, tagpath): - """ returns the children of the given path, only with given type """ - node = self.getNode(tagpath) - try: - return filter(lambda x:x.nodeType == x.ELEMENT_NODE, - node.childNodes) - except AttributeError: - return None - - # write helpers - - def addNode(self, tagPath, newnode = None): - "this adds the newnode under given tag path" - self.verifyRootTag() - return addNode(self.doc.documentElement, tagPath, newnode) - - def addNodeUnder(self, node, tagPath, newnode = None): - "this adds the new stuff under node and then following tag path" - self.verifyRootTag() - return addNode(node, tagPath, newnode) - - def addChild(self, newnode): - "add a new child node right under root element document" - self.doc.documentElement.appendChild(newnode) - - def addText(self, node, text): - "add text to node" - node.appendChild(self.newTextNode(text)) - - def addTextNode(self, tagPath, text): - "add a text node with given tag path" - node = self.addNode(tagPath, self.newTextNode(text)) - return node - - def addTextNodeUnder(self, node, tagPath, text): - "add a text node under given node with tag path (phew)" - return self.addNodeUnder(node, tagPath, self.newTextNode(text)) diff --git a/pisi/pxml/xmlfilepiks.py b/pisi/pxml/xmlfilepiks.py deleted file mode 100644 index 15355940..00000000 --- a/pisi/pxml/xmlfilepiks.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2005, TUBITAK/UEKAE -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at your option) -# any later version. -# -# Please read the COPYING file. -# - -""" - XmlFile class further abstracts a dom object using the - high-level dom functions provided in xmlext module (and sorely lacking - in xml.dom :( ) - - function names are mixedCase for compatibility with minidom, - an 'old library' - - this implementation uses piksemel -""" - -import gettext -__trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext - -import codecs -import exceptions - -import piksemel as iks - -import pisi -from pisi.file import File -from pisi.util import join_path as join - -class Error(pisi.Error): - pass - -class XmlFile(object): - """A class to help reading and writing an XML file""" - - def __init__(self, tag): - self.rootTag = tag - - def newDocument(self): - """clear DOM""" - self.doc = iks.newDocument(self.rootTag) - - def unlink(self): - """deallocate DOM structure""" - del self.doc - - def rootNode(self): - """returns root document element""" - return self.doc - - def readxmlfile(self, file): - raise Exception("not implemented") - try: - self.doc = iks.parse(file) - return self.doc - except Exception, e: - raise Error(_("File '%s' has invalid XML") % (localpath) ) - - - def readxml(self, uri, tmpDir='/tmp', sha1sum=False, - compress=None, sign=None, copylocal = False): - uri = File.make_uri(uri) - #try: - localpath = File.download(uri, tmpDir, sha1sum=sha1sum, - compress=compress,sign=sign, copylocal=copylocal) - #except IOError, e: - # raise Error(_("Cannot read URI %s: %s") % (uri, unicode(e)) ) - try: - self.doc = iks.parse(localpath) - return self.doc - except Exception, e: - raise Error(_("File '%s' has invalid XML") % (localpath) ) - - def writexml(self, uri, tmpDir = '/tmp', sha1sum=False, compress=None, sign=None): - f = File(uri, File.write, sha1sum=sha1sum, compress=compress, sign=sign) - f.write(self.doc.toPrettyString()) - f.close() - - def writexmlfile(self, f): - f.write(self.doc.toPrettyString())