2016-03-01 62 views
1

我得到了這段代碼,我試圖讀取所有'ref''href'標籤。我不知道如何使這不區分大小寫,因爲我的一些xml文件有REF或Ref或ref。 有什麼建議嗎?不區分大小寫的xml和python

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] 
+0

聽起來像你需要修復XML,因爲它被解析,所以一旦它被加載到根中的情況是規範化的 - 例如在這裏看到nonagon的答案如何獲取標記,因爲他們被解析,確保你可以找出如何小寫它們http://stackoverflow.com/questions/13412496/python-elementtree-module-how-to-ignore-the-namespace-of-xml-files-to-locate-ma/33997423#33997423 – barny

+0

也看到答案在這裏 - 不是最微妙的技術,但得到的一切都是相同的情況 - http://stackoverflow.com/questions/9440896/case-insensitive-findall-in-python-elementtree – barny

回答

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] 
0

如果您正在使用lxml那麼一種選擇是使用XPath通過XSLT擴展正則表達式(https://stackoverflow.com/a/2756994/2997179):

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

您可以正常化標籤和屬性通過使用以下功能將它們轉換爲小寫字母作爲預處理步驟:

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)) 
+0

謝謝隊友,它工作正常其中大多數,但一些我得到一個錯誤:xml.etree.ElementTree.ParseError:不匹配的標記:第4行,第5列 – Adam