不区分大小写的xml和python

时间:2016-03-01 11:44:49

标签: python xml python-2.7

我收到了这段代码,而我正在尝试阅读所有' ref' ' HREF'标签。我不知道如何使这个不区分大小写,因为我的一些xml文件有REF或Ref或ref。 有什么建议吗?

    f = urllib.urlopen(url)
    tree = ET.parse(f)
    root = tree.getroot()

    for child in root.iter('ref'):
      t = child.get('href')
      if t not in self.href:
        self.href.append(t)
        print self.href[-1]

3 个答案:

答案 0 :(得分:3)

您可以使用以下函数将标记和属性转换为小写来规范化标记和属性,作为预处理步骤:

import xml.etree.ElementTree as ET
f = urllib.urlopen(url)
tree = ET.parse(f)
root = tree.getroot()

def normalize_tags(root):
    root.tag = root.tag.lower()
    for child in root:
        normalize_tags(child)

def normalize_attr(root):
    for attr,value in root.attrib.items():
        norm_attr = attr.lower()
        if norm_attr != attr:
            root.set(norm_attr,value)
            root.attrib.pop(attr)

    for child in root:
        normalize_attr(child)


normalize_tags(root)    
normalize_attr(root)
print(ET.tostring(root))

答案 1 :(得分:0)

以下内容应该有所帮助

f = urllib.urlopen(url)
tree = ET.parse(f)
root = tree.getroot()

for child in root:
  if child.tag.lower() == 'ref':
    t = child.attribute.get('href')
    if t not in self.href:
      self.href.append(t)
      print self.href[-1]

答案 2 :(得分:0)

如果您正在使用lxml,那么一个选项是通过XSLT扩展(https://stackoverflow.com/a/2756994/2997179)将XPath与正则表达式一起使用:

root.xpath("./*[re:test(local-name(), '(?i)href')]",
    namespaces={"re": "http://exslt.org/regular-expressions"})
相关问题