expunge the xmlcore changes:

41667, 41668 - initial switch to xmlcore
  47044        - mention of xmlcore in What's New
  50687        - mention of xmlcore in the library reference

re-apply xmlcore changes to xml:
  41674        - line ending changes (re-applied manually), directory props
  41677        - add cElementTree wrapper
  41678        - PSF licensing for etree
  41812        - whitespace normalization
  42724        - fix svn:eol-style settings
  43681, 43682 - remove Python version-compatibility cruft from minidom
  46773        - fix encoding of \r\n\t in attr values in saxutils
  47269        - added XMLParser alias for cElementTree compatibility

additional tests were added in Lib/test/test_sax.py that failed with
the xmlcore changes; these relate to SF bugs #1511497, #1513611
This commit is contained in:
Fred Drake 2006-07-29 16:56:15 +00:00
parent c032ee939b
commit fbdeaad069
31 changed files with 253 additions and 250 deletions

View File

@ -15,17 +15,6 @@ You may still want to be aware of the \ulink{PyXML add-on
package}{http://pyxml.sourceforge.net/}; that package provides an package}{http://pyxml.sourceforge.net/}; that package provides an
extended set of XML libraries for Python. extended set of XML libraries for Python.
Python 2.5 introduces the \module{xmlcore} package; this package
provides the implementation of the \module{xml} package as distributed
with the standard library. The \module{xml} package, as in earlier
versions, provides an interface that will provide the PyXML
implementation of the interfaces when available, and the standard
library implementation if not. Applications that can use either the
PyXML implementation or the standard library's implementation may
continue to make imports from the \module{xml} package; applications
that want to only import the standard library's implementation can now
use the \module{xmlcore} package.
The documentation for the \module{xml.dom} and \module{xml.sax} The documentation for the \module{xml.dom} and \module{xml.sax}
packages are the definition of the Python bindings for the DOM and SAX packages are the definition of the Python bindings for the DOM and SAX
interfaces. interfaces.

View File

@ -1760,13 +1760,6 @@ Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg
Brandl.) Brandl.)
% Patch #754022 % Patch #754022
\item The standard library's XML-related package
has been renamed to \module{xmlcore}. The \module{xml} module will
now import either the \module{xmlcore} or PyXML version of subpackages
such as \module{xml.dom}. The renaming means it will always be
possible to import the standard library's XML support whether or not
the PyXML package is installed.
\item The \module{xmlrpclib} module now supports returning \item The \module{xmlrpclib} module now supports returning
\class{datetime} objects for the XML-RPC date type. Supply \class{datetime} objects for the XML-RPC date type. Supply
\code{use_datetime=True} to the \function{loads()} function \code{use_datetime=True} to the \function{loads()} function
@ -2404,10 +2397,6 @@ to allow only \code{'/'} and \code{'/RPC2'}. Setting
\member{rpc_paths} to \code{None} or an empty tuple disables \member{rpc_paths} to \code{None} or an empty tuple disables
this path checking. this path checking.
\item Library: the \module{xml} package has been renamed to \module{xmlcore}.
The PyXML package will therefore be \module{xml}, and the Python
distribution's code will always be accessible as \module{xmlcore}.
\item C API: Many functions now use \ctype{Py_ssize_t} \item C API: Many functions now use \ctype{Py_ssize_t}
instead of \ctype{int} to allow processing more data on 64-bit instead of \ctype{int} to allow processing more data on 64-bit
machines. Extension code may need to make the same change to avoid machines. Extension code may need to make the same change to avoid

View File

@ -1,4 +1,4 @@
# test for xmlcore.dom.minidom # test for xml.dom.minidom
import os import os
import sys import sys
@ -7,12 +7,12 @@ import traceback
from StringIO import StringIO from StringIO import StringIO
from test.test_support import verbose from test.test_support import verbose
import xmlcore.dom import xml.dom
import xmlcore.dom.minidom import xml.dom.minidom
import xmlcore.parsers.expat import xml.parsers.expat
from xmlcore.dom.minidom import parse, Node, Document, parseString from xml.dom.minidom import parse, Node, Document, parseString
from xmlcore.dom.minidom import getDOMImplementation from xml.dom.minidom import getDOMImplementation
if __name__ == "__main__": if __name__ == "__main__":
@ -138,29 +138,29 @@ def testLegalChildren():
text = dom.createTextNode('text') text = dom.createTextNode('text')
try: dom.appendChild(text) try: dom.appendChild(text)
except xmlcore.dom.HierarchyRequestErr: pass except xml.dom.HierarchyRequestErr: pass
else: else:
print "dom.appendChild didn't raise HierarchyRequestErr" print "dom.appendChild didn't raise HierarchyRequestErr"
dom.appendChild(elem) dom.appendChild(elem)
try: dom.insertBefore(text, elem) try: dom.insertBefore(text, elem)
except xmlcore.dom.HierarchyRequestErr: pass except xml.dom.HierarchyRequestErr: pass
else: else:
print "dom.appendChild didn't raise HierarchyRequestErr" print "dom.appendChild didn't raise HierarchyRequestErr"
try: dom.replaceChild(text, elem) try: dom.replaceChild(text, elem)
except xmlcore.dom.HierarchyRequestErr: pass except xml.dom.HierarchyRequestErr: pass
else: else:
print "dom.appendChild didn't raise HierarchyRequestErr" print "dom.appendChild didn't raise HierarchyRequestErr"
nodemap = elem.attributes nodemap = elem.attributes
try: nodemap.setNamedItem(text) try: nodemap.setNamedItem(text)
except xmlcore.dom.HierarchyRequestErr: pass except xml.dom.HierarchyRequestErr: pass
else: else:
print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr" print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"
try: nodemap.setNamedItemNS(text) try: nodemap.setNamedItemNS(text)
except xmlcore.dom.HierarchyRequestErr: pass except xml.dom.HierarchyRequestErr: pass
else: else:
print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr" print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"
@ -439,7 +439,7 @@ def testProcessingInstruction():
and pi.firstChild is None and pi.firstChild is None
and pi.lastChild is None and pi.lastChild is None
and pi.localName is None and pi.localName is None
and pi.namespaceURI == xmlcore.dom.EMPTY_NAMESPACE) and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE)
def testProcessingInstructionRepr(): pass def testProcessingInstructionRepr(): pass
@ -454,7 +454,7 @@ def testTooManyDocumentElements():
elem = doc.createElement("extra") elem = doc.createElement("extra")
try: try:
doc.appendChild(elem) doc.appendChild(elem)
except xmlcore.dom.HierarchyRequestErr: except xml.dom.HierarchyRequestErr:
pass pass
else: else:
print "Failed to catch expected exception when" \ print "Failed to catch expected exception when" \
@ -491,7 +491,7 @@ def testRemoveNamedItem():
confirm(a1.isSameNode(a2)) confirm(a1.isSameNode(a2))
try: try:
attrs.removeNamedItem("a") attrs.removeNamedItem("a")
except xmlcore.dom.NotFoundErr: except xml.dom.NotFoundErr:
pass pass
def testRemoveNamedItemNS(): def testRemoveNamedItemNS():
@ -503,7 +503,7 @@ def testRemoveNamedItemNS():
confirm(a1.isSameNode(a2)) confirm(a1.isSameNode(a2))
try: try:
attrs.removeNamedItemNS("http://xml.python.org/", "b") attrs.removeNamedItemNS("http://xml.python.org/", "b")
except xmlcore.dom.NotFoundErr: except xml.dom.NotFoundErr:
pass pass
def testAttrListValues(): pass def testAttrListValues(): pass
@ -682,7 +682,7 @@ def check_import_document(deep, testName):
doc2 = parseString("<doc/>") doc2 = parseString("<doc/>")
try: try:
doc1.importNode(doc2, deep) doc1.importNode(doc2, deep)
except xmlcore.dom.NotSupportedErr: except xml.dom.NotSupportedErr:
pass pass
else: else:
raise Exception(testName + raise Exception(testName +
@ -705,12 +705,10 @@ def create_nonempty_doctype():
doctype = getDOMImplementation().createDocumentType("doc", None, None) doctype = getDOMImplementation().createDocumentType("doc", None, None)
doctype.entities._seq = [] doctype.entities._seq = []
doctype.notations._seq = [] doctype.notations._seq = []
notation = xmlcore.dom.minidom.Notation( notation = xml.dom.minidom.Notation("my-notation", None,
"my-notation", None,
"http://xml.python.org/notations/my") "http://xml.python.org/notations/my")
doctype.notations._seq.append(notation) doctype.notations._seq.append(notation)
entity = xmlcore.dom.minidom.Entity( entity = xml.dom.minidom.Entity("my-entity", None,
"my-entity", None,
"http://xml.python.org/entities/my", "http://xml.python.org/entities/my",
"my-notation") "my-notation")
entity.version = "1.0" entity.version = "1.0"
@ -731,7 +729,7 @@ def testImportDocumentTypeShallow():
target = create_doc_without_doctype() target = create_doc_without_doctype()
try: try:
imported = target.importNode(src.doctype, 0) imported = target.importNode(src.doctype, 0)
except xmlcore.dom.NotSupportedErr: except xml.dom.NotSupportedErr:
pass pass
else: else:
raise Exception( raise Exception(
@ -742,7 +740,7 @@ def testImportDocumentTypeDeep():
target = create_doc_without_doctype() target = create_doc_without_doctype()
try: try:
imported = target.importNode(src.doctype, 1) imported = target.importNode(src.doctype, 1)
except xmlcore.dom.NotSupportedErr: except xml.dom.NotSupportedErr:
pass pass
else: else:
raise Exception( raise Exception(
@ -850,7 +848,7 @@ def testNodeListItem():
doc.unlink() doc.unlink()
def testSAX2DOM(): def testSAX2DOM():
from xmlcore.dom import pulldom from xml.dom import pulldom
sax2dom = pulldom.SAX2DOM() sax2dom = pulldom.SAX2DOM()
sax2dom.startDocument() sax2dom.startDocument()
@ -940,11 +938,11 @@ def testRenameAttribute():
attr = elem.attributes['a'] attr = elem.attributes['a']
# Simple renaming # Simple renaming
attr = doc.renameNode(attr, xmlcore.dom.EMPTY_NAMESPACE, "b") attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
confirm(attr.name == "b" confirm(attr.name == "b"
and attr.nodeName == "b" and attr.nodeName == "b"
and attr.localName is None and attr.localName is None
and attr.namespaceURI == xmlcore.dom.EMPTY_NAMESPACE and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
and attr.prefix is None and attr.prefix is None
and attr.value == "v" and attr.value == "v"
and elem.getAttributeNode("a") is None and elem.getAttributeNode("a") is None
@ -989,11 +987,11 @@ def testRenameAttribute():
and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr)) and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
# Rename back to a simple non-NS node # Rename back to a simple non-NS node
attr = doc.renameNode(attr, xmlcore.dom.EMPTY_NAMESPACE, "e") attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
confirm(attr.name == "e" confirm(attr.name == "e"
and attr.nodeName == "e" and attr.nodeName == "e"
and attr.localName is None and attr.localName is None
and attr.namespaceURI == xmlcore.dom.EMPTY_NAMESPACE and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
and attr.prefix is None and attr.prefix is None
and attr.value == "v" and attr.value == "v"
and elem.getAttributeNode("a") is None and elem.getAttributeNode("a") is None
@ -1007,7 +1005,7 @@ def testRenameAttribute():
try: try:
doc.renameNode(attr, "http://xml.python.org/ns", "xmlns") doc.renameNode(attr, "http://xml.python.org/ns", "xmlns")
except xmlcore.dom.NamespaceErr: except xml.dom.NamespaceErr:
pass pass
else: else:
print "expected NamespaceErr" print "expected NamespaceErr"
@ -1020,11 +1018,11 @@ def testRenameElement():
elem = doc.documentElement elem = doc.documentElement
# Simple renaming # Simple renaming
elem = doc.renameNode(elem, xmlcore.dom.EMPTY_NAMESPACE, "a") elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
confirm(elem.tagName == "a" confirm(elem.tagName == "a"
and elem.nodeName == "a" and elem.nodeName == "a"
and elem.localName is None and elem.localName is None
and elem.namespaceURI == xmlcore.dom.EMPTY_NAMESPACE and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None and elem.prefix is None
and elem.ownerDocument.isSameNode(doc)) and elem.ownerDocument.isSameNode(doc))
@ -1047,11 +1045,11 @@ def testRenameElement():
and elem.ownerDocument.isSameNode(doc)) and elem.ownerDocument.isSameNode(doc))
# Rename back to a simple non-NS node # Rename back to a simple non-NS node
elem = doc.renameNode(elem, xmlcore.dom.EMPTY_NAMESPACE, "d") elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
confirm(elem.tagName == "d" confirm(elem.tagName == "d"
and elem.nodeName == "d" and elem.nodeName == "d"
and elem.localName is None and elem.localName is None
and elem.namespaceURI == xmlcore.dom.EMPTY_NAMESPACE and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None and elem.prefix is None
and elem.ownerDocument.isSameNode(doc)) and elem.ownerDocument.isSameNode(doc))
@ -1062,15 +1060,15 @@ def checkRenameNodeSharedConstraints(doc, node):
# Make sure illegal NS usage is detected: # Make sure illegal NS usage is detected:
try: try:
doc.renameNode(node, "http://xml.python.org/ns", "xmlns:foo") doc.renameNode(node, "http://xml.python.org/ns", "xmlns:foo")
except xmlcore.dom.NamespaceErr: except xml.dom.NamespaceErr:
pass pass
else: else:
print "expected NamespaceErr" print "expected NamespaceErr"
doc2 = parseString("<doc/>") doc2 = parseString("<doc/>")
try: try:
doc2.renameNode(node, xmlcore.dom.EMPTY_NAMESPACE, "foo") doc2.renameNode(node, xml.dom.EMPTY_NAMESPACE, "foo")
except xmlcore.dom.WrongDocumentErr: except xml.dom.WrongDocumentErr:
pass pass
else: else:
print "expected WrongDocumentErr" print "expected WrongDocumentErr"
@ -1078,12 +1076,12 @@ def checkRenameNodeSharedConstraints(doc, node):
def testRenameOther(): def testRenameOther():
# We have to create a comment node explicitly since not all DOM # We have to create a comment node explicitly since not all DOM
# builders used with minidom add comments to the DOM. # builders used with minidom add comments to the DOM.
doc = xmlcore.dom.minidom.getDOMImplementation().createDocument( doc = xml.dom.minidom.getDOMImplementation().createDocument(
xmlcore.dom.EMPTY_NAMESPACE, "e", None) xml.dom.EMPTY_NAMESPACE, "e", None)
node = doc.createComment("comment") node = doc.createComment("comment")
try: try:
doc.renameNode(node, xmlcore.dom.EMPTY_NAMESPACE, "foo") doc.renameNode(node, xml.dom.EMPTY_NAMESPACE, "foo")
except xmlcore.dom.NotSupportedErr: except xml.dom.NotSupportedErr:
pass pass
else: else:
print "expected NotSupportedErr when renaming comment node" print "expected NotSupportedErr when renaming comment node"
@ -1194,13 +1192,13 @@ def testSchemaType():
# since each supports a different level of DTD information. # since each supports a different level of DTD information.
t = elem.schemaType t = elem.schemaType
confirm(t.name is None confirm(t.name is None
and t.namespace == xmlcore.dom.EMPTY_NAMESPACE) and t.namespace == xml.dom.EMPTY_NAMESPACE)
names = "id notid text enum ref refs ent ents nm nms".split() names = "id notid text enum ref refs ent ents nm nms".split()
for name in names: for name in names:
a = elem.getAttributeNode(name) a = elem.getAttributeNode(name)
t = a.schemaType t = a.schemaType
confirm(hasattr(t, "name") confirm(hasattr(t, "name")
and t.namespace == xmlcore.dom.EMPTY_NAMESPACE) and t.namespace == xml.dom.EMPTY_NAMESPACE)
def testSetIdAttribute(): def testSetIdAttribute():
doc = parseString("<doc a1='v' a2='w'/>") doc = parseString("<doc a1='v' a2='w'/>")
@ -1229,7 +1227,7 @@ def testSetIdAttribute():
and a2.isId and a2.isId
and not a3.isId) and not a3.isId)
# renaming an attribute should not affect its ID-ness: # renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xmlcore.dom.EMPTY_NAMESPACE, "an") doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
confirm(e.isSameNode(doc.getElementById("w")) confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId) and a2.isId)
@ -1265,7 +1263,7 @@ def testSetIdAttributeNS():
confirm(not a3.isId) confirm(not a3.isId)
confirm(doc.getElementById("v") is None) confirm(doc.getElementById("v") is None)
# renaming an attribute should not affect its ID-ness: # renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xmlcore.dom.EMPTY_NAMESPACE, "an") doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
confirm(e.isSameNode(doc.getElementById("w")) confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId) and a2.isId)
@ -1301,7 +1299,7 @@ def testSetIdAttributeNode():
confirm(not a3.isId) confirm(not a3.isId)
confirm(doc.getElementById("v") is None) confirm(doc.getElementById("v") is None)
# renaming an attribute should not affect its ID-ness: # renaming an attribute should not affect its ID-ness:
doc.renameNode(a2, xmlcore.dom.EMPTY_NAMESPACE, "an") doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
confirm(e.isSameNode(doc.getElementById("w")) confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId) and a2.isId)

View File

@ -1,17 +1,17 @@
# regression test for SAX 2.0 -*- coding: iso-8859-1 -*- # regression test for SAX 2.0 -*- coding: iso-8859-1 -*-
# $Id$ # $Id$
from xmlcore.sax import make_parser, ContentHandler, \ from xml.sax import make_parser, ContentHandler, \
SAXException, SAXReaderNotAvailable, SAXParseException SAXException, SAXReaderNotAvailable, SAXParseException
try: try:
make_parser() make_parser()
except SAXReaderNotAvailable: except SAXReaderNotAvailable:
# don't try to test this module if we cannot create a parser # don't try to test this module if we cannot create a parser
raise ImportError("no XML parsers available") raise ImportError("no XML parsers available")
from xmlcore.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \ from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \
XMLFilterBase XMLFilterBase
from xmlcore.sax.expatreader import create_parser from xml.sax.expatreader import create_parser
from xmlcore.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
from cStringIO import StringIO from cStringIO import StringIO
from test.test_support import verify, verbose, TestFailed, findfile from test.test_support import verify, verbose, TestFailed, findfile
import os import os
@ -36,17 +36,17 @@ def test_make_parser2():
# Creating parsers several times in a row should succeed. # Creating parsers several times in a row should succeed.
# Testing this because there have been failures of this kind # Testing this because there have been failures of this kind
# before. # before.
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
from xmlcore.sax import make_parser from xml.sax import make_parser
p = make_parser() p = make_parser()
except: except:
return 0 return 0
@ -108,7 +108,7 @@ def test_make_parser():
try: try:
# Creating a parser should succeed - it should fall back # Creating a parser should succeed - it should fall back
# to the expatreader # to the expatreader
p = make_parser(['xmlcore.parsers.no_such_parser']) p = make_parser(['xml.parsers.no_such_parser'])
except: except:
return 0 return 0
else: else:
@ -671,6 +671,55 @@ def test_nsattrs_wattr():
attrs.getQNameByName((ns_uri, "attr")) == "ns:attr" attrs.getQNameByName((ns_uri, "attr")) == "ns:attr"
# During the development of Python 2.5, an attempt to move the "xml"
# package implementation to a new package ("xmlcore") proved painful.
# The goal of this change was to allow applications to be able to
# obtain and rely on behavior in the standard library implementation
# of the XML support without needing to be concerned about the
# availability of the PyXML implementation.
#
# While the existing import hackery in Lib/xml/__init__.py can cause
# PyXML's _xmlpus package to supplant the "xml" package, that only
# works because either implementation uses the "xml" package name for
# imports.
#
# The move resulted in a number of problems related to the fact that
# the import machinery's "package context" is based on the name that's
# being imported rather than the __name__ of the actual package
# containment; it wasn't possible for the "xml" package to be replaced
# by a simple module that indirected imports to the "xmlcore" package.
#
# The following two tests exercised bugs that were introduced in that
# attempt. Keeping these tests around will help detect problems with
# other attempts to provide reliable access to the standard library's
# implementation of the XML support.
def test_sf_1511497():
# Bug report: http://www.python.org/sf/1511497
import sys
old_modules = sys.modules.copy()
for modname in sys.modules.keys():
if modname.startswith("xml."):
del sys.modules[modname]
try:
import xml.sax.expatreader
module = xml.sax.expatreader
return module.__name__ == "xml.sax.expatreader"
finally:
sys.modules.update(old_modules)
def test_sf_1513611():
# Bug report: http://www.python.org/sf/1513611
sio = StringIO("invalid")
parser = make_parser()
from xml.sax import SAXParseException
try:
parser.parse(sio)
except SAXParseException:
return True
else:
return False
# ===== Main program # ===== Main program
def make_test_output(): def make_test_output():

View File

@ -1,4 +1,4 @@
# xmlcore.etree test. This file contains enough tests to make sure that # xml.etree test. This file contains enough tests to make sure that
# all included components work as they should. For a more extensive # all included components work as they should. For a more extensive
# test suite, see the selftest script in the ElementTree distribution. # test suite, see the selftest script in the ElementTree distribution.
@ -6,8 +6,6 @@ import doctest, sys
from test import test_support from test import test_support
from xmlcore.etree import ElementTree as ET
SAMPLE_XML = """ SAMPLE_XML = """
<body> <body>
<tag>text</tag> <tag>text</tag>
@ -32,9 +30,9 @@ def sanity():
""" """
Import sanity. Import sanity.
>>> from xmlcore.etree import ElementTree >>> from xml.etree import ElementTree
>>> from xmlcore.etree import ElementInclude >>> from xml.etree import ElementInclude
>>> from xmlcore.etree import ElementPath >>> from xml.etree import ElementPath
""" """
def check_method(method): def check_method(method):
@ -61,6 +59,8 @@ def interface():
""" """
Test element tree interface. Test element tree interface.
>>> from xml.etree import ElementTree as ET
>>> element = ET.Element("tag", key="value") >>> element = ET.Element("tag", key="value")
>>> tree = ET.ElementTree(element) >>> tree = ET.ElementTree(element)
@ -108,6 +108,8 @@ def find():
""" """
Test find methods (including xpath syntax). Test find methods (including xpath syntax).
>>> from xml.etree import ElementTree as ET
>>> elem = ET.XML(SAMPLE_XML) >>> elem = ET.XML(SAMPLE_XML)
>>> elem.find("tag").tag >>> elem.find("tag").tag
'tag' 'tag'
@ -174,6 +176,8 @@ def find():
def parseliteral(): def parseliteral():
r""" r"""
>>> from xml.etree import ElementTree as ET
>>> element = ET.XML("<html><body>text</body></html>") >>> element = ET.XML("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout) >>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html> <html><body>text</body></html>
@ -195,19 +199,6 @@ def parseliteral():
'body' 'body'
""" """
def check_encoding(encoding):
"""
>>> check_encoding("ascii")
>>> check_encoding("us-ascii")
>>> check_encoding("iso-8859-1")
>>> check_encoding("iso-8859-15")
>>> check_encoding("cp437")
>>> check_encoding("mac-roman")
"""
ET.XML(
"<?xml version='1.0' encoding='%s'?><xml />" % encoding
)
# #
# xinclude tests (samples from appendix C of the xinclude specification) # xinclude tests (samples from appendix C of the xinclude specification)
@ -282,14 +273,16 @@ def xinclude_loader(href, parse="xml", encoding=None):
except KeyError: except KeyError:
raise IOError("resource not found") raise IOError("resource not found")
if parse == "xml": if parse == "xml":
return ET.XML(data) from xml.etree.ElementTree import XML
return XML(data)
return data return data
def xinclude(): def xinclude():
r""" r"""
Basic inclusion example (XInclude C.1) Basic inclusion example (XInclude C.1)
>>> from xmlcore.etree import ElementInclude >>> from xml.etree import ElementTree as ET
>>> from xml.etree import ElementInclude
>>> document = xinclude_loader("C1.xml") >>> document = xinclude_loader("C1.xml")
>>> ElementInclude.include(document, xinclude_loader) >>> ElementInclude.include(document, xinclude_loader)

View File

@ -1,10 +1,10 @@
# xmlcore.etree test for cElementTree # xml.etree test for cElementTree
import doctest, sys import doctest, sys
from test import test_support from test import test_support
from xmlcore.etree import cElementTree as ET from xml.etree import cElementTree as ET
SAMPLE_XML = """ SAMPLE_XML = """
<body> <body>
@ -30,7 +30,7 @@ def sanity():
""" """
Import sanity. Import sanity.
>>> from xmlcore.etree import cElementTree >>> from xml.etree import cElementTree
""" """
def check_method(method): def check_method(method):

View File

@ -16,8 +16,6 @@ etree -- The ElementTree XML library. This is a subset of the full
""" """
import sys
import xmlcore
__all__ = ["dom", "parsers", "sax", "etree"] __all__ = ["dom", "parsers", "sax", "etree"]
@ -29,10 +27,11 @@ __version__ = "$Revision$".split()[-2:][0]
_MINIMUM_XMLPLUS_VERSION = (0, 8, 4) _MINIMUM_XMLPLUS_VERSION = (0, 8, 4)
try: try:
import _xmlplus import _xmlplus
except ImportError: except ImportError:
sys.modules[__name__] = xmlcore pass
else: else:
try: try:
v = _xmlplus.version_info v = _xmlplus.version_info
@ -41,7 +40,8 @@ else:
pass pass
else: else:
if v >= _MINIMUM_XMLPLUS_VERSION: if v >= _MINIMUM_XMLPLUS_VERSION:
_xmlplus.__path__.extend(xmlcore.__path__) import sys
_xmlplus.__path__.extend(__path__)
sys.modules[__name__] = _xmlplus sys.modules[__name__] = _xmlplus
else: else:
del v del v

View File

@ -2,7 +2,7 @@
directly. Instead, the functions getDOMImplementation and directly. Instead, the functions getDOMImplementation and
registerDOMImplementation should be imported from xml.dom.""" registerDOMImplementation should be imported from xml.dom."""
from xmlcore.dom.minicompat import * # isinstance, StringTypes from xml.dom.minicompat import * # isinstance, StringTypes
# This is a list of well-known implementations. Well-known names # This is a list of well-known implementations. Well-known names
# should be published by posting to xml-sig@python.org, and are # should be published by posting to xml-sig@python.org, and are

View File

@ -27,13 +27,13 @@ This avoids all the overhead of SAX and pulldom to gain performance.
# calling any methods on the node object if it exists. (A rather # calling any methods on the node object if it exists. (A rather
# nice speedup is achieved this way as well!) # nice speedup is achieved this way as well!)
from xmlcore.dom import xmlbuilder, minidom, Node from xml.dom import xmlbuilder, minidom, Node
from xmlcore.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE
from xmlcore.parsers import expat from xml.parsers import expat
from xmlcore.dom.minidom import _append_child, _set_attribute_node from xml.dom.minidom import _append_child, _set_attribute_node
from xmlcore.dom.NodeFilter import NodeFilter from xml.dom.NodeFilter import NodeFilter
from xmlcore.dom.minicompat import * from xml.dom.minicompat import *
TEXT_NODE = Node.TEXT_NODE TEXT_NODE = Node.TEXT_NODE
CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE

View File

@ -38,7 +38,7 @@
__all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] __all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"]
import xmlcore.dom import xml.dom
try: try:
unicode unicode
@ -71,6 +71,7 @@ class NodeList(list):
def __setstate__(self, state): def __setstate__(self, state):
self[:] = state self[:] = state
class EmptyNodeList(tuple): class EmptyNodeList(tuple):
__slots__ = () __slots__ = ()

View File

@ -14,22 +14,22 @@ Todo:
* SAX 2 namespaces * SAX 2 namespaces
""" """
import xmlcore.dom import xml.dom
from xmlcore.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
from xmlcore.dom.minicompat import * from xml.dom.minicompat import *
from xmlcore.dom.xmlbuilder import DOMImplementationLS, DocumentLS from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
# This is used by the ID-cache invalidation checks; the list isn't # This is used by the ID-cache invalidation checks; the list isn't
# actually complete, since the nodes being checked will never be the # actually complete, since the nodes being checked will never be the
# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
# the node being added or removed, not the node being modified.) # the node being added or removed, not the node being modified.)
# #
_nodeTypes_with_children = (xmlcore.dom.Node.ELEMENT_NODE, _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
xmlcore.dom.Node.ENTITY_REFERENCE_NODE) xml.dom.Node.ENTITY_REFERENCE_NODE)
class Node(xmlcore.dom.Node): class Node(xml.dom.Node):
namespaceURI = None # this is non-null only for elements and attributes namespaceURI = None # this is non-null only for elements and attributes
parentNode = None parentNode = None
ownerDocument = None ownerDocument = None
@ -83,7 +83,7 @@ class Node(xmlcore.dom.Node):
### The DOM does not clearly specify what to return in this case ### The DOM does not clearly specify what to return in this case
return newChild return newChild
if newChild.nodeType not in self._child_node_types: if newChild.nodeType not in self._child_node_types:
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(newChild), repr(self))) "%s cannot be child of %s" % (repr(newChild), repr(self)))
if newChild.parentNode is not None: if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild) newChild.parentNode.removeChild(newChild)
@ -93,7 +93,7 @@ class Node(xmlcore.dom.Node):
try: try:
index = self.childNodes.index(refChild) index = self.childNodes.index(refChild)
except ValueError: except ValueError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
if newChild.nodeType in _nodeTypes_with_children: if newChild.nodeType in _nodeTypes_with_children:
_clear_id_cache(self) _clear_id_cache(self)
self.childNodes.insert(index, newChild) self.childNodes.insert(index, newChild)
@ -115,7 +115,7 @@ class Node(xmlcore.dom.Node):
### The DOM does not clearly specify what to return in this case ### The DOM does not clearly specify what to return in this case
return node return node
if node.nodeType not in self._child_node_types: if node.nodeType not in self._child_node_types:
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self))) "%s cannot be child of %s" % (repr(node), repr(self)))
elif node.nodeType in _nodeTypes_with_children: elif node.nodeType in _nodeTypes_with_children:
_clear_id_cache(self) _clear_id_cache(self)
@ -131,7 +131,7 @@ class Node(xmlcore.dom.Node):
self.removeChild(oldChild) self.removeChild(oldChild)
return self.insertBefore(newChild, refChild) return self.insertBefore(newChild, refChild)
if newChild.nodeType not in self._child_node_types: if newChild.nodeType not in self._child_node_types:
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(newChild), repr(self))) "%s cannot be child of %s" % (repr(newChild), repr(self)))
if newChild is oldChild: if newChild is oldChild:
return return
@ -140,7 +140,7 @@ class Node(xmlcore.dom.Node):
try: try:
index = self.childNodes.index(oldChild) index = self.childNodes.index(oldChild)
except ValueError: except ValueError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
self.childNodes[index] = newChild self.childNodes[index] = newChild
newChild.parentNode = self newChild.parentNode = self
oldChild.parentNode = None oldChild.parentNode = None
@ -161,7 +161,7 @@ class Node(xmlcore.dom.Node):
try: try:
self.childNodes.remove(oldChild) self.childNodes.remove(oldChild)
except ValueError: except ValueError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
if oldChild.nextSibling is not None: if oldChild.nextSibling is not None:
oldChild.nextSibling.previousSibling = oldChild.previousSibling oldChild.nextSibling.previousSibling = oldChild.previousSibling
if oldChild.previousSibling is not None: if oldChild.previousSibling is not None:
@ -386,7 +386,7 @@ class Attr(Node):
nsuri = self.namespaceURI nsuri = self.namespaceURI
if prefix == "xmlns": if prefix == "xmlns":
if nsuri and nsuri != XMLNS_NAMESPACE: if nsuri and nsuri != XMLNS_NAMESPACE:
raise xmlcore.dom.NamespaceErr( raise xml.dom.NamespaceErr(
"illegal use of 'xmlns' prefix for the wrong namespace") "illegal use of 'xmlns' prefix for the wrong namespace")
d = self.__dict__ d = self.__dict__
d['prefix'] = prefix d['prefix'] = prefix
@ -564,7 +564,7 @@ class NamedNodeMap(object):
n.__dict__['ownerElement'] = None n.__dict__['ownerElement'] = None
return n return n
else: else:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
def removeNamedItemNS(self, namespaceURI, localName): def removeNamedItemNS(self, namespaceURI, localName):
n = self.getNamedItemNS(namespaceURI, localName) n = self.getNamedItemNS(namespaceURI, localName)
@ -576,11 +576,11 @@ class NamedNodeMap(object):
n.__dict__['ownerElement'] = None n.__dict__['ownerElement'] = None
return n return n
else: else:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
def setNamedItem(self, node): def setNamedItem(self, node):
if not isinstance(node, Attr): if not isinstance(node, Attr):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self))) "%s cannot be child of %s" % (repr(node), repr(self)))
old = self._attrs.get(node.name) old = self._attrs.get(node.name)
if old: if old:
@ -731,7 +731,7 @@ class Element(Node):
def setAttributeNode(self, attr): def setAttributeNode(self, attr):
if attr.ownerElement not in (None, self): if attr.ownerElement not in (None, self):
raise xmlcore.dom.InuseAttributeErr("attribute node already owned") raise xml.dom.InuseAttributeErr("attribute node already owned")
old1 = self._attrs.get(attr.name, None) old1 = self._attrs.get(attr.name, None)
if old1 is not None: if old1 is not None:
self.removeAttributeNode(old1) self.removeAttributeNode(old1)
@ -753,23 +753,23 @@ class Element(Node):
try: try:
attr = self._attrs[name] attr = self._attrs[name]
except KeyError: except KeyError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
self.removeAttributeNode(attr) self.removeAttributeNode(attr)
def removeAttributeNS(self, namespaceURI, localName): def removeAttributeNS(self, namespaceURI, localName):
try: try:
attr = self._attrsNS[(namespaceURI, localName)] attr = self._attrsNS[(namespaceURI, localName)]
except KeyError: except KeyError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
self.removeAttributeNode(attr) self.removeAttributeNode(attr)
def removeAttributeNode(self, node): def removeAttributeNode(self, node):
if node is None: if node is None:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
try: try:
self._attrs[node.name] self._attrs[node.name]
except KeyError: except KeyError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
_clear_id_cache(self) _clear_id_cache(self)
node.unlink() node.unlink()
# Restore this since the node is still useful and otherwise # Restore this since the node is still useful and otherwise
@ -837,9 +837,9 @@ class Element(Node):
def setIdAttributeNode(self, idAttr): def setIdAttributeNode(self, idAttr):
if idAttr is None or not self.isSameNode(idAttr.ownerElement): if idAttr is None or not self.isSameNode(idAttr.ownerElement):
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
if _get_containing_entref(self) is not None: if _get_containing_entref(self) is not None:
raise xmlcore.dom.NoModificationAllowedErr() raise xml.dom.NoModificationAllowedErr()
if not idAttr._is_id: if not idAttr._is_id:
idAttr.__dict__['_is_id'] = True idAttr.__dict__['_is_id'] = True
self._magic_id_nodes += 1 self._magic_id_nodes += 1
@ -880,22 +880,22 @@ class Childless:
return None return None
def appendChild(self, node): def appendChild(self, node):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes cannot have children") self.nodeName + " nodes cannot have children")
def hasChildNodes(self): def hasChildNodes(self):
return False return False
def insertBefore(self, newChild, refChild): def insertBefore(self, newChild, refChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes do not have children") self.nodeName + " nodes do not have children")
def removeChild(self, oldChild): def removeChild(self, oldChild):
raise xmlcore.dom.NotFoundErr( raise xml.dom.NotFoundErr(
self.nodeName + " nodes do not have children") self.nodeName + " nodes do not have children")
def replaceChild(self, newChild, oldChild): def replaceChild(self, newChild, oldChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes do not have children") self.nodeName + " nodes do not have children")
@ -961,11 +961,11 @@ class CharacterData(Childless, Node):
def substringData(self, offset, count): def substringData(self, offset, count):
if offset < 0: if offset < 0:
raise xmlcore.dom.IndexSizeErr("offset cannot be negative") raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data): if offset >= len(self.data):
raise xmlcore.dom.IndexSizeErr("offset cannot be beyond end of data") raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0: if count < 0:
raise xmlcore.dom.IndexSizeErr("count cannot be negative") raise xml.dom.IndexSizeErr("count cannot be negative")
return self.data[offset:offset+count] return self.data[offset:offset+count]
def appendData(self, arg): def appendData(self, arg):
@ -973,30 +973,30 @@ class CharacterData(Childless, Node):
def insertData(self, offset, arg): def insertData(self, offset, arg):
if offset < 0: if offset < 0:
raise xmlcore.dom.IndexSizeErr("offset cannot be negative") raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data): if offset >= len(self.data):
raise xmlcore.dom.IndexSizeErr("offset cannot be beyond end of data") raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if arg: if arg:
self.data = "%s%s%s" % ( self.data = "%s%s%s" % (
self.data[:offset], arg, self.data[offset:]) self.data[:offset], arg, self.data[offset:])
def deleteData(self, offset, count): def deleteData(self, offset, count):
if offset < 0: if offset < 0:
raise xmlcore.dom.IndexSizeErr("offset cannot be negative") raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data): if offset >= len(self.data):
raise xmlcore.dom.IndexSizeErr("offset cannot be beyond end of data") raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0: if count < 0:
raise xmlcore.dom.IndexSizeErr("count cannot be negative") raise xml.dom.IndexSizeErr("count cannot be negative")
if count: if count:
self.data = self.data[:offset] + self.data[offset+count:] self.data = self.data[:offset] + self.data[offset+count:]
def replaceData(self, offset, count, arg): def replaceData(self, offset, count, arg):
if offset < 0: if offset < 0:
raise xmlcore.dom.IndexSizeErr("offset cannot be negative") raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data): if offset >= len(self.data):
raise xmlcore.dom.IndexSizeErr("offset cannot be beyond end of data") raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0: if count < 0:
raise xmlcore.dom.IndexSizeErr("count cannot be negative") raise xml.dom.IndexSizeErr("count cannot be negative")
if count: if count:
self.data = "%s%s%s" % ( self.data = "%s%s%s" % (
self.data[:offset], arg, self.data[offset+count:]) self.data[:offset], arg, self.data[offset+count:])
@ -1016,7 +1016,7 @@ class Text(CharacterData):
def splitText(self, offset): def splitText(self, offset):
if offset < 0 or offset > len(self.data): if offset < 0 or offset > len(self.data):
raise xmlcore.dom.IndexSizeErr("illegal offset value") raise xml.dom.IndexSizeErr("illegal offset value")
newText = self.__class__() newText = self.__class__()
newText.data = self.data[offset:] newText.data = self.data[offset:]
newText.ownerDocument = self.ownerDocument newText.ownerDocument = self.ownerDocument
@ -1185,19 +1185,19 @@ class ReadOnlySequentialNamedNodeMap(object):
return None return None
def removeNamedItem(self, name): def removeNamedItem(self, name):
raise xmlcore.dom.NoModificationAllowedErr( raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only") "NamedNodeMap instance is read-only")
def removeNamedItemNS(self, namespaceURI, localName): def removeNamedItemNS(self, namespaceURI, localName):
raise xmlcore.dom.NoModificationAllowedErr( raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only") "NamedNodeMap instance is read-only")
def setNamedItem(self, node): def setNamedItem(self, node):
raise xmlcore.dom.NoModificationAllowedErr( raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only") "NamedNodeMap instance is read-only")
def setNamedItemNS(self, node): def setNamedItemNS(self, node):
raise xmlcore.dom.NoModificationAllowedErr( raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only") "NamedNodeMap instance is read-only")
def __getstate__(self): def __getstate__(self):
@ -1251,7 +1251,7 @@ class DocumentType(Identified, Childless, Node):
clone = DocumentType(None) clone = DocumentType(None)
clone.name = self.name clone.name = self.name
clone.nodeName = self.name clone.nodeName = self.name
operation = xmlcore.dom.UserDataHandler.NODE_CLONED operation = xml.dom.UserDataHandler.NODE_CLONED
if deep: if deep:
clone.entities._seq = [] clone.entities._seq = []
clone.notations._seq = [] clone.notations._seq = []
@ -1311,19 +1311,19 @@ class Entity(Identified, Node):
return self.version return self.version
def appendChild(self, newChild): def appendChild(self, newChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"cannot append children to an entity node") "cannot append children to an entity node")
def insertBefore(self, newChild, refChild): def insertBefore(self, newChild, refChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"cannot insert children below an entity node") "cannot insert children below an entity node")
def removeChild(self, oldChild): def removeChild(self, oldChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"cannot remove children from an entity node") "cannot remove children from an entity node")
def replaceChild(self, newChild, oldChild): def replaceChild(self, newChild, oldChild):
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"cannot replace children of an entity node") "cannot replace children of an entity node")
class Notation(Identified, Childless, Node): class Notation(Identified, Childless, Node):
@ -1355,7 +1355,7 @@ class DOMImplementation(DOMImplementationLS):
def createDocument(self, namespaceURI, qualifiedName, doctype): def createDocument(self, namespaceURI, qualifiedName, doctype):
if doctype and doctype.parentNode is not None: if doctype and doctype.parentNode is not None:
raise xmlcore.dom.WrongDocumentErr( raise xml.dom.WrongDocumentErr(
"doctype object owned by another DOM tree") "doctype object owned by another DOM tree")
doc = self._create_document() doc = self._create_document()
@ -1376,15 +1376,15 @@ class DOMImplementation(DOMImplementationLS):
# Null the document is returned without a document element # Null the document is returned without a document element
# Otherwise if doctype or namespaceURI are not None # Otherwise if doctype or namespaceURI are not None
# Then we go back to the above problem # Then we go back to the above problem
raise xmlcore.dom.InvalidCharacterErr("Element with no name") raise xml.dom.InvalidCharacterErr("Element with no name")
if add_root_element: if add_root_element:
prefix, localname = _nssplit(qualifiedName) prefix, localname = _nssplit(qualifiedName)
if prefix == "xml" \ if prefix == "xml" \
and namespaceURI != "http://www.w3.org/XML/1998/namespace": and namespaceURI != "http://www.w3.org/XML/1998/namespace":
raise xmlcore.dom.NamespaceErr("illegal use of 'xml' prefix") raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
if prefix and not namespaceURI: if prefix and not namespaceURI:
raise xmlcore.dom.NamespaceErr( raise xml.dom.NamespaceErr(
"illegal use of prefix without namespaces") "illegal use of prefix without namespaces")
element = doc.createElementNS(namespaceURI, qualifiedName) element = doc.createElementNS(namespaceURI, qualifiedName)
if doctype: if doctype:
@ -1533,7 +1533,7 @@ class Document(Node, DocumentLS):
def appendChild(self, node): def appendChild(self, node):
if node.nodeType not in self._child_node_types: if node.nodeType not in self._child_node_types:
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self))) "%s cannot be child of %s" % (repr(node), repr(self)))
if node.parentNode is not None: if node.parentNode is not None:
# This needs to be done before the next test since this # This needs to be done before the next test since this
@ -1543,7 +1543,7 @@ class Document(Node, DocumentLS):
if node.nodeType == Node.ELEMENT_NODE \ if node.nodeType == Node.ELEMENT_NODE \
and self._get_documentElement(): and self._get_documentElement():
raise xmlcore.dom.HierarchyRequestErr( raise xml.dom.HierarchyRequestErr(
"two document elements disallowed") "two document elements disallowed")
return Node.appendChild(self, node) return Node.appendChild(self, node)
@ -1551,7 +1551,7 @@ class Document(Node, DocumentLS):
try: try:
self.childNodes.remove(oldChild) self.childNodes.remove(oldChild)
except ValueError: except ValueError:
raise xmlcore.dom.NotFoundErr() raise xml.dom.NotFoundErr()
oldChild.nextSibling = oldChild.previousSibling = None oldChild.nextSibling = oldChild.previousSibling = None
oldChild.parentNode = None oldChild.parentNode = None
if self.documentElement is oldChild: if self.documentElement is oldChild:
@ -1587,7 +1587,7 @@ class Document(Node, DocumentLS):
assert clone.doctype is None assert clone.doctype is None
clone.doctype = childclone clone.doctype = childclone
childclone.parentNode = clone childclone.parentNode = clone
self._call_user_data_handler(xmlcore.dom.UserDataHandler.NODE_CLONED, self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
self, clone) self, clone)
return clone return clone
@ -1729,9 +1729,9 @@ class Document(Node, DocumentLS):
def importNode(self, node, deep): def importNode(self, node, deep):
if node.nodeType == Node.DOCUMENT_NODE: if node.nodeType == Node.DOCUMENT_NODE:
raise xmlcore.dom.NotSupportedErr("cannot import document nodes") raise xml.dom.NotSupportedErr("cannot import document nodes")
elif node.nodeType == Node.DOCUMENT_TYPE_NODE: elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
raise xmlcore.dom.NotSupportedErr("cannot import document type nodes") raise xml.dom.NotSupportedErr("cannot import document type nodes")
return _clone_node(node, deep, self) return _clone_node(node, deep, self)
def writexml(self, writer, indent="", addindent="", newl="", def writexml(self, writer, indent="", addindent="", newl="",
@ -1747,24 +1747,24 @@ class Document(Node, DocumentLS):
def renameNode(self, n, namespaceURI, name): def renameNode(self, n, namespaceURI, name):
if n.ownerDocument is not self: if n.ownerDocument is not self:
raise xmlcore.dom.WrongDocumentErr( raise xml.dom.WrongDocumentErr(
"cannot rename nodes from other documents;\n" "cannot rename nodes from other documents;\n"
"expected %s,\nfound %s" % (self, n.ownerDocument)) "expected %s,\nfound %s" % (self, n.ownerDocument))
if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
raise xmlcore.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"renameNode() only applies to element and attribute nodes") "renameNode() only applies to element and attribute nodes")
if namespaceURI != EMPTY_NAMESPACE: if namespaceURI != EMPTY_NAMESPACE:
if ':' in name: if ':' in name:
prefix, localName = name.split(':', 1) prefix, localName = name.split(':', 1)
if ( prefix == "xmlns" if ( prefix == "xmlns"
and namespaceURI != xmlcore.dom.XMLNS_NAMESPACE): and namespaceURI != xml.dom.XMLNS_NAMESPACE):
raise xmlcore.dom.NamespaceErr( raise xml.dom.NamespaceErr(
"illegal use of 'xmlns' prefix") "illegal use of 'xmlns' prefix")
else: else:
if ( name == "xmlns" if ( name == "xmlns"
and namespaceURI != xmlcore.dom.XMLNS_NAMESPACE and namespaceURI != xml.dom.XMLNS_NAMESPACE
and n.nodeType == Node.ATTRIBUTE_NODE): and n.nodeType == Node.ATTRIBUTE_NODE):
raise xmlcore.dom.NamespaceErr( raise xml.dom.NamespaceErr(
"illegal use of the 'xmlns' attribute") "illegal use of the 'xmlns' attribute")
prefix = None prefix = None
localName = name localName = name
@ -1810,9 +1810,9 @@ def _clone_node(node, deep, newOwnerDocument):
Called by Node.cloneNode and Document.importNode Called by Node.cloneNode and Document.importNode
""" """
if node.ownerDocument.isSameNode(newOwnerDocument): if node.ownerDocument.isSameNode(newOwnerDocument):
operation = xmlcore.dom.UserDataHandler.NODE_CLONED operation = xml.dom.UserDataHandler.NODE_CLONED
else: else:
operation = xmlcore.dom.UserDataHandler.NODE_IMPORTED operation = xml.dom.UserDataHandler.NODE_IMPORTED
if node.nodeType == Node.ELEMENT_NODE: if node.nodeType == Node.ELEMENT_NODE:
clone = newOwnerDocument.createElementNS(node.namespaceURI, clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName) node.nodeName)
@ -1849,7 +1849,7 @@ def _clone_node(node, deep, newOwnerDocument):
clone.value = node.value clone.value = node.value
elif node.nodeType == Node.DOCUMENT_TYPE_NODE: elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
assert node.ownerDocument is not newOwnerDocument assert node.ownerDocument is not newOwnerDocument
operation = xmlcore.dom.UserDataHandler.NODE_IMPORTED operation = xml.dom.UserDataHandler.NODE_IMPORTED
clone = newOwnerDocument.implementation.createDocumentType( clone = newOwnerDocument.implementation.createDocumentType(
node.name, node.publicId, node.systemId) node.name, node.publicId, node.systemId)
clone.ownerDocument = newOwnerDocument clone.ownerDocument = newOwnerDocument
@ -1876,7 +1876,7 @@ def _clone_node(node, deep, newOwnerDocument):
# Note the cloning of Document and DocumentType nodes is # Note the cloning of Document and DocumentType nodes is
# implemenetation specific. minidom handles those cases # implemenetation specific. minidom handles those cases
# directly in the cloneNode() methods. # directly in the cloneNode() methods.
raise xmlcore.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
# Check for _call_user_data_handler() since this could conceivably # Check for _call_user_data_handler() since this could conceivably
# used with other DOM implementations (one of the FourThought # used with other DOM implementations (one of the FourThought
@ -1909,20 +1909,20 @@ def _do_pulldom_parse(func, args, kwargs):
def parse(file, parser=None, bufsize=None): def parse(file, parser=None, bufsize=None):
"""Parse a file into a DOM by filename or file object.""" """Parse a file into a DOM by filename or file object."""
if parser is None and not bufsize: if parser is None and not bufsize:
from xmlcore.dom import expatbuilder from xml.dom import expatbuilder
return expatbuilder.parse(file) return expatbuilder.parse(file)
else: else:
from xmlcore.dom import pulldom from xml.dom import pulldom
return _do_pulldom_parse(pulldom.parse, (file,), return _do_pulldom_parse(pulldom.parse, (file,),
{'parser': parser, 'bufsize': bufsize}) {'parser': parser, 'bufsize': bufsize})
def parseString(string, parser=None): def parseString(string, parser=None):
"""Parse a file into a DOM from a string.""" """Parse a file into a DOM from a string."""
if parser is None: if parser is None:
from xmlcore.dom import expatbuilder from xml.dom import expatbuilder
return expatbuilder.parseString(string) return expatbuilder.parseString(string)
else: else:
from xmlcore.dom import pulldom from xml.dom import pulldom
return _do_pulldom_parse(pulldom.parseString, (string,), return _do_pulldom_parse(pulldom.parseString, (string,),
{'parser': parser}) {'parser': parser})

View File

@ -1,5 +1,5 @@
import xmlcore.sax import xml.sax
import xmlcore.sax.handler import xml.sax.handler
import types import types
try: try:
@ -16,12 +16,12 @@ PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION"
IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE" IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE"
CHARACTERS = "CHARACTERS" CHARACTERS = "CHARACTERS"
class PullDOM(xmlcore.sax.ContentHandler): class PullDOM(xml.sax.ContentHandler):
_locator = None _locator = None
document = None document = None
def __init__(self, documentFactory=None): def __init__(self, documentFactory=None):
from xmlcore.dom import XML_NAMESPACE from xml.dom import XML_NAMESPACE
self.documentFactory = documentFactory self.documentFactory = documentFactory
self.firstEvent = [None, None] self.firstEvent = [None, None]
self.lastEvent = self.firstEvent self.lastEvent = self.firstEvent
@ -164,8 +164,8 @@ class PullDOM(xmlcore.sax.ContentHandler):
def startDocument(self): def startDocument(self):
if self.documentFactory is None: if self.documentFactory is None:
import xmlcore.dom.minidom import xml.dom.minidom
self.documentFactory = xmlcore.dom.minidom.Document.implementation self.documentFactory = xml.dom.minidom.Document.implementation
def buildDocument(self, uri, tagname): def buildDocument(self, uri, tagname):
# Can't do that in startDocument, since we need the tagname # Can't do that in startDocument, since we need the tagname
@ -219,7 +219,7 @@ class DOMEventStream:
def reset(self): def reset(self):
self.pulldom = PullDOM() self.pulldom = PullDOM()
# This content handler relies on namespace support # This content handler relies on namespace support
self.parser.setFeature(xmlcore.sax.handler.feature_namespaces, 1) self.parser.setFeature(xml.sax.handler.feature_namespaces, 1)
self.parser.setContentHandler(self.pulldom) self.parser.setContentHandler(self.pulldom)
def __getitem__(self, pos): def __getitem__(self, pos):
@ -335,7 +335,7 @@ def parse(stream_or_string, parser=None, bufsize=None):
else: else:
stream = stream_or_string stream = stream_or_string
if not parser: if not parser:
parser = xmlcore.sax.make_parser() parser = xml.sax.make_parser()
return DOMEventStream(stream, parser, bufsize) return DOMEventStream(stream, parser, bufsize)
def parseString(string, parser=None): def parseString(string, parser=None):
@ -347,5 +347,5 @@ def parseString(string, parser=None):
bufsize = len(string) bufsize = len(string)
buf = StringIO(string) buf = StringIO(string)
if not parser: if not parser:
parser = xmlcore.sax.make_parser() parser = xml.sax.make_parser()
return DOMEventStream(buf, parser, bufsize) return DOMEventStream(buf, parser, bufsize)

View File

@ -1,9 +1,9 @@
"""Implementation of the DOM Level 3 'LS-Load' feature.""" """Implementation of the DOM Level 3 'LS-Load' feature."""
import copy import copy
import xmlcore.dom import xml.dom
from xmlcore.dom.NodeFilter import NodeFilter from xml.dom.NodeFilter import NodeFilter
__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"]
@ -78,13 +78,13 @@ class DOMBuilder:
try: try:
settings = self._settings[(_name_xform(name), state)] settings = self._settings[(_name_xform(name), state)]
except KeyError: except KeyError:
raise xmlcore.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"unsupported feature: %r" % (name,)) "unsupported feature: %r" % (name,))
else: else:
for name, value in settings: for name, value in settings:
setattr(self._options, name, value) setattr(self._options, name, value)
else: else:
raise xmlcore.dom.NotFoundErr("unknown feature: " + repr(name)) raise xml.dom.NotFoundErr("unknown feature: " + repr(name))
def supportsFeature(self, name): def supportsFeature(self, name):
return hasattr(self._options, _name_xform(name)) return hasattr(self._options, _name_xform(name))
@ -175,7 +175,7 @@ class DOMBuilder:
or options.create_entity_ref_nodes or options.create_entity_ref_nodes
or options.entities or options.entities
or options.cdata_sections)) or options.cdata_sections))
raise xmlcore.dom.NotFoundErr("feature %s not known" % repr(name)) raise xml.dom.NotFoundErr("feature %s not known" % repr(name))
def parseURI(self, uri): def parseURI(self, uri):
if self.entityResolver: if self.entityResolver:
@ -200,8 +200,8 @@ class DOMBuilder:
raise NotImplementedError("Haven't written this yet...") raise NotImplementedError("Haven't written this yet...")
def _parse_bytestream(self, stream, options): def _parse_bytestream(self, stream, options):
import xmlcore.dom.expatbuilder import xml.dom.expatbuilder
builder = xmlcore.dom.expatbuilder.makeBuilder(options) builder = xml.dom.expatbuilder.makeBuilder(options)
return builder.parseFile(stream) return builder.parseFile(stream)
@ -340,7 +340,7 @@ class DocumentLS:
return False return False
def _set_async(self, async): def _set_async(self, async):
if async: if async:
raise xmlcore.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"asynchronous document loading is not supported") "asynchronous document loading is not supported")
def abort(self): def abort(self):
@ -359,7 +359,7 @@ class DocumentLS:
if snode is None: if snode is None:
snode = self snode = self
elif snode.ownerDocument is not self: elif snode.ownerDocument is not self:
raise xmlcore.dom.WrongDocumentErr() raise xml.dom.WrongDocumentErr()
return snode.toxml() return snode.toxml()
@ -369,12 +369,12 @@ class DOMImplementationLS:
def createDOMBuilder(self, mode, schemaType): def createDOMBuilder(self, mode, schemaType):
if schemaType is not None: if schemaType is not None:
raise xmlcore.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"schemaType not yet supported") "schemaType not yet supported")
if mode == self.MODE_SYNCHRONOUS: if mode == self.MODE_SYNCHRONOUS:
return DOMBuilder() return DOMBuilder()
if mode == self.MODE_ASYNCHRONOUS: if mode == self.MODE_ASYNCHRONOUS:
raise xmlcore.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"asynchronous builders are not supported") "asynchronous builders are not supported")
raise ValueError("unknown value for mode") raise ValueError("unknown value for mode")

View File

@ -1112,7 +1112,7 @@ class XMLTreeBuilder:
def __init__(self, html=0, target=None): def __init__(self, html=0, target=None):
try: try:
from xmlcore.parsers import expat from xml.parsers import expat
except ImportError: except ImportError:
raise ImportError( raise ImportError(
"No module named expat; use SimpleXMLTreeBuilder instead" "No module named expat; use SimpleXMLTreeBuilder instead"
@ -1194,7 +1194,7 @@ class XMLTreeBuilder:
try: try:
self._target.data(self.entity[text[1:-1]]) self._target.data(self.entity[text[1:-1]])
except KeyError: except KeyError:
from xmlcore.parsers import expat from xml.parsers import expat
raise expat.error( raise expat.error(
"undefined entity %s: line %d, column %d" % "undefined entity %s: line %d, column %d" %
(text, self._parser.ErrorLineNumber, (text, self._parser.ErrorLineNumber,

View File

@ -51,12 +51,12 @@ def parseString(string, handler, errorHandler=ErrorHandler()):
# this is the parser list used by the make_parser function if no # this is the parser list used by the make_parser function if no
# alternatives are given as parameters to the function # alternatives are given as parameters to the function
default_parser_list = ["xmlcore.sax.expatreader"] default_parser_list = ["xml.sax.expatreader"]
# tell modulefinder that importing sax potentially imports expatreader # tell modulefinder that importing sax potentially imports expatreader
_false = 0 _false = 0
if _false: if _false:
import xmlcore.sax.expatreader import xml.sax.expatreader
import os, sys import os, sys
if os.environ.has_key("PY_SAX_PARSER"): if os.environ.has_key("PY_SAX_PARSER"):

View File

@ -5,27 +5,27 @@ pyexpat.__version__ == '2.22'.
version = "0.20" version = "0.20"
from xmlcore.sax._exceptions import * from xml.sax._exceptions import *
from xmlcore.sax.handler import feature_validation, feature_namespaces from xml.sax.handler import feature_validation, feature_namespaces
from xmlcore.sax.handler import feature_namespace_prefixes from xml.sax.handler import feature_namespace_prefixes
from xmlcore.sax.handler import feature_external_ges, feature_external_pes from xml.sax.handler import feature_external_ges, feature_external_pes
from xmlcore.sax.handler import feature_string_interning from xml.sax.handler import feature_string_interning
from xmlcore.sax.handler import property_xml_string, property_interning_dict from xml.sax.handler import property_xml_string, property_interning_dict
# xmlcore.parsers.expat does not raise ImportError in Jython # xml.parsers.expat does not raise ImportError in Jython
import sys import sys
if sys.platform[:4] == "java": if sys.platform[:4] == "java":
raise SAXReaderNotAvailable("expat not available in Java", None) raise SAXReaderNotAvailable("expat not available in Java", None)
del sys del sys
try: try:
from xmlcore.parsers import expat from xml.parsers import expat
except ImportError: except ImportError:
raise SAXReaderNotAvailable("expat not supported", None) raise SAXReaderNotAvailable("expat not supported", None)
else: else:
if not hasattr(expat, "ParserCreate"): if not hasattr(expat, "ParserCreate"):
raise SAXReaderNotAvailable("expat not supported", None) raise SAXReaderNotAvailable("expat not supported", None)
from xmlcore.sax import xmlreader, saxutils, handler from xml.sax import xmlreader, saxutils, handler
AttributesImpl = xmlreader.AttributesImpl AttributesImpl = xmlreader.AttributesImpl
AttributesNSImpl = xmlreader.AttributesNSImpl AttributesNSImpl = xmlreader.AttributesNSImpl
@ -407,8 +407,8 @@ def create_parser(*args, **kwargs):
# --- # ---
if __name__ == "__main__": if __name__ == "__main__":
import xmlcore.sax import xml.sax
p = create_parser() p = create_parser()
p.setContentHandler(xmlcore.sax.XMLGenerator()) p.setContentHandler(xml.sax.XMLGenerator())
p.setErrorHandler(xmlcore.sax.ErrorHandler()) p.setErrorHandler(xml.sax.ErrorHandler())
p.parse("../../../hamlet.xml") p.parse("../../../hamlet.xml")

View File

@ -1,20 +0,0 @@
"""Core XML support for Python.
This package contains four sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This
supports the SAX 2 API.
etree -- The ElementTree XML library. This is a subset of the full
ElementTree XML release.
"""
__all__ = ["dom", "parsers", "sax", "etree"]

View File

@ -695,7 +695,7 @@ PLATDIR= plat-$(MACHDEP)
EXTRAPLATDIR= @EXTRAPLATDIR@ EXTRAPLATDIR= @EXTRAPLATDIR@
EXTRAMACHDEPPATH=@EXTRAMACHDEPPATH@ EXTRAMACHDEPPATH=@EXTRAMACHDEPPATH@
MACHDEPS= $(PLATDIR) $(EXTRAPLATDIR) MACHDEPS= $(PLATDIR) $(EXTRAPLATDIR)
XMLLIBSUBDIRS= xmlcore xmlcore/dom xmlcore/etree xmlcore/parsers xmlcore/sax XMLLIBSUBDIRS= xml xml/dom xml/etree xml/parsers xml/sax
PLATMACDIRS= plat-mac plat-mac/Carbon plat-mac/lib-scriptpackages \ PLATMACDIRS= plat-mac plat-mac/Carbon plat-mac/lib-scriptpackages \
plat-mac/lib-scriptpackages/_builtinSuites \ plat-mac/lib-scriptpackages/_builtinSuites \
plat-mac/lib-scriptpackages/CodeWarrior \ plat-mac/lib-scriptpackages/CodeWarrior \

View File

@ -52,6 +52,10 @@ Core and builtins
Library Library
------- -------
- Rename of the xml package to xmlcore, and the import hackery done to
make it appear at both names, has been removed. Bug #1511497,
#1513611, and probably others.
- Bug #1441397: The compiler module now recognizes module and function - Bug #1441397: The compiler module now recognizes module and function
docstrings correctly as it did in Python 2.4. docstrings correctly as it did in Python 2.4.
@ -1640,8 +1644,8 @@ Library
- Bug #792570: SimpleXMLRPCServer had problems if the request grew too large. - Bug #792570: SimpleXMLRPCServer had problems if the request grew too large.
Fixed by reading the HTTP body in chunks instead of one big socket.read(). Fixed by reading the HTTP body in chunks instead of one big socket.read().
- Patches #893642, #1039083: add allow_none, encoding arguments to constructors of - Patches #893642, #1039083: add allow_none, encoding arguments to
SimpleXMLRPCServer and CGIXMLRPCRequestHandler. constructors of SimpleXMLRPCServer and CGIXMLRPCRequestHandler.
- Bug #1110478: Revert os.environ.update to do putenv again. - Bug #1110478: Revert os.environ.update to do putenv again.