我有一组要解析的超简单XML文件...但是...它们使用自定义定义的实体。我不需要将它们映射到字符,但是我确实希望对每个字符进行解析和操作。例如:
<Style name="admin-5678">
<Rule>
<Filter>[admin_level]='5'</Filter>
&maxscale_zoom11;
</Rule>
</Style>
在http://effbot.org/elementtree/elementtree-xmlparser.htm上有一个诱人的暗示,即XMLParser有限的实体支持,但是我找不到所提到的方法,所有的东西都会出错:
#!/usr/bin/python
##
## Where's the entity support as documented at:
## http://effbot.org/elementtree/elementtree-xmlparser.htm
## In Python 2.7.1+ ?
##
from pprint import pprint
from xml.etree import ElementTree
from cStringIO import StringIO
parser = ElementTree.ElementTree()
#parser.entity["maxscale_zoom11"] = unichr(160)
testf = StringIO('<foo>&maxscale_zoom11;</foo>')
tree = parser.parse(testf)
#tree = parser.parse(testf,"XMLParser")
for node in tree.iter('foo'):
print node.text
取决于您如何调整注释而得出:
xml.etree.ElementTree.ParseError: undefined entity: line 1, column 5
要么
AttributeError: 'ElementTree' object has no attribute 'entity'
要么
AttributeError: 'str' object has no attribute 'feed'
对于那些好奇的人来说,XML来自OpenStreetMap的mapnik项目。
最佳答案
我不确定这是否是ElementTree中的错误还是什么,但是您需要在expat解析器上调用UseForeignDTD(True)来恢复过去的行为。
这有点hacky,但是您可以通过创建自己的ElementTree.Parser实例,在xml.parsers.expat实例上调用该方法,然后将其传递给ElementTree.parse()来实现:
from xml.etree import ElementTree
from cStringIO import StringIO
testf = StringIO('<foo>&moo_1;</foo>')
parser = ElementTree.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity['moo_1'] = 'MOOOOO'
etree = ElementTree.ElementTree()
tree = etree.parse(testf, parser=parser)
for node in tree.iter('foo'):
print node.text
输出“MOOOOO”
或使用映射接口(interface):
from xml.etree import ElementTree
from cStringIO import StringIO
class AllEntities:
def __getitem__(self, key):
#key is your entity, you can do whatever you want with it here
return key
testf = StringIO('<foo>&moo_1;</foo>')
parser = ElementTree.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity = AllEntities()
etree = ElementTree.ElementTree()
tree = etree.parse(testf, parser=parser)
for node in tree.iter('foo'):
print node.text
输出“moo_1”
更复杂的修复方法是将ElementTree.XMLParser子类化并在那里进行修复。
关于python - Python ElementTree支持解析未知的XML实体吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7237466/