如何使用 lxml 解析包含前缀但没有命名空间声明的 XML? [英] How to parse XML containing prefixes but no namespace declarations with lxml?

查看:58
本文介绍了如何使用 lxml 解析包含前缀但没有命名空间声明的 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆使用前缀但没有相应命名空间声明的 XML 文件.

类似的东西:

...</tal:block>

或:

...

我知道这些前缀的来源,我尝试了以下方法,但没有成功:

from lxml import etree as ElementTreeElementTree.register_namespace("i18n", "http://namespaces.zope.org")ElementTree.register_namespace("tal", "http://xml.zope.org/namespaces/tal")使用 open(path) 作为 fp:树 = ElementTree.parse(fp)

但 lxml 仍然窒息:

lxml.etree.XMLSyntaxError:未定义 div 上域的命名空间前缀 i18n,第 4 行,第 20 列

我知道我可以使用 ElementTree.XMLParser(recover=True),但我还是想保留前缀,而这个方法没有.

有什么想法吗?

解决方案

它不是有效的 XML,使用未定义的前缀,因此没有 XML 解析器能够处理它.

您最好的选择(除了修复 XML)是以编程方式修改 XML 源以将命名空间属性添加到根元素(仅使用您的语言中的字符串支持).在将 XML 提供给解析器之前,将 xmlns:tal="http://xml.zope.org/namespaces/tal" 等添加到根元素.然后 XML 解析器应该毫无怨言地处理它,也无需注册任何命名空间.

I have a bunch of XML files which are using prefixes but without the corresponding namespace declaration.

Stuff like:

<tal:block tal:condition="foo">
...
</tal:block>

or:

<div i18n:domain="my-app">
...

I know where those prefixes come from, an I tried the following, but without success:

from lxml import etree as ElementTree

ElementTree.register_namespace("i18n", "http://namespaces.zope.org")
ElementTree.register_namespace("tal", "http://xml.zope.org/namespaces/tal")

with open(path) as fp:
    tree = ElementTree.parse(fp)

but lxml still chokes with:

lxml.etree.XMLSyntaxError: Namespace prefix i18n for domain on div is not defined, line 4, column 20

I know I can use ElementTree.XMLParser(recover=True), but I would like to keep the prefix anyway, which this method don't.

Any idea?

解决方案

It's not valid XML, using undefined prefixes, so no XML parser is going to be able to deal with it.

Your best bet (other than fixing the XML) is to programmaticly modify the XML source to add the namespace attributes to the root element (just using the string support in your language). Add xmlns:tal="http://xml.zope.org/namespaces/tal", etc to the root element before you give the XML to the parser. Then the XML parser should handle it without complaint and without any registering namespaces.

这篇关于如何使用 lxml 解析包含前缀但没有命名空间声明的 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆