java 解析带前缀xml,如何使用lxml解析包含前缀但不包含名称空间声明的XML?

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

Stuff like:

...

or:

...

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值