Using SimpleXMLTreeBuilder in elementtree

佐手、 提交于 2019-11-27 16:10:27

If you have third party module that wants to use ElementTree (and XMLTreeBuilder by dependency) you can change ElementTree's XMLTreeBuilder definition to the one provided by SimpleXMLTreeBuilder like so:

from xml.etree import ElementTree # part of python distribution
from elementtree import SimpleXMLTreeBuilder # part of your codebase
ElementTree.XMLTreeBuilder = SimpleXMLTreeBuilder.TreeBuilder

Now ElementTree will always use the SimpleXMLTreeBuilder whenever it's called.

See also: http://groups.google.com/group/google-appengine/browse_thread/thread/b7399a91c9525c97

We ran into this same problem using python version 2.6.4 on CentOS 5.5.

The issue happens when the expat class attempts to load the pyexpat modules, see /usr/lib64/python2.6/xml/parsers/expat.py

Looking inside of /usr/lib64/python2.6/lib-dynload/, I didn't see the "pyexpat.so" shared object. However, I did see it on another machine, which wasn't having the problem.

I compared the python versions (yum list 'python*') and identified that the properly functioning machine had python 2.6.5. Running 'yum update python26' fixed the issue for me.

If that doesn't work for you and you want a slapstick solution, you can copy the SO file into your dynamic load path.

Assuming you're now using elementtree.XMLTreeBuilder, just try this instead:

from elementtree import SimpleXMLTreeBuilder as XMLTreeBuilder

It tries to provide exactly the same functionality but using xmllib instead of expat. If that also fails, BTW, try:

from elementtree import SgmlopXMLTreeBuilder as XMLTreeBuilder

to attempt to use yet another implementation, this one based on sgmlop instead.

from elementtree import SimpleXMLTreeBuilder as XMLTreeBuilder

Ok, it has slightly changed now:

Traceback (most recent call last):
  File "C:\Python26\tests\xml.py", line 12, in <module>
    doc = elementtree.ElementTree.parse("foo.xml")
  File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 908, in parse
    tree = parser_api.parse(source)
  File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 169, in parse
    parser = XMLTreeBuilder()
  File "C:\Python26\lib\site-packages\elementtree\ElementTree.py", line 1165, in __init__
    "No module named expat; use SimpleXMLTreeBuilder instead"
ImportError: No module named expat; use SimpleXMLTreeBuilder instead

I think it was statically linked with older version of Python or something. Is there an easy way to attach XML parser to Python 2.6? Some libraries seem to only work with older versions 8(

I have same error as you when I developed on Solaris & python 2.7.2. I fixed this issue after I installed the python expat package by using pkgin. See if the solution above can give you any idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!