xml python findall_Python ElementTree模块:当使用方法“find”,“findall”时如何忽略XML文件的命名空间来定位匹配元素。...

I want to use the method of "findall" to locate some elements of the source xml file in the ElementTree module.

However, the source xml file (test.xml) has namespace. I truncate part of xml file as sample:

Updates

9/26/2012 10:30:34 AM

All Rights Reserved.

newlicense.htm

N

The sample python code is below:

from xml.etree import ElementTree as ET

tree = ET.parse(r"test.xml")

el1 = tree.findall("DEAL_LEVEL/PAID_OFF") # Return None

el2 = tree.findall("{http://www.test.com}DEAL_LEVEL/{http://www.test.com}PAID_OFF") # Return

Although it can works, because there is a namespace "{http://www.test.com}", it's very inconvenient to add a namespace in front of each tag.

How can I ignore the namespace when using the method of "find", "findall" and so on?

解决方案

Instead of modifying the XML document itself, it's best to parse it and then modify the tags in the result. This way you can handle multiple namespaces and namespace aliases:

from StringIO import StringIO

import xml.etree.ElementTree as ET

# instead of ET.fromstring(xml)

it = ET.iterparse(StringIO(xml))

for _, el in it:

if '}' in el.tag:

el.tag = el.tag.split('}', 1)[1] # strip all namespaces

root = it.root

This is based on the discussion here:

http://bugs.python.org/issue18304

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值