2013-08-05 8 views
6

Sto tentando di aprire un file xml e ottenere valori da determinati tag. L'ho fatto molto ma questo particolare xml mi sta dando dei problemi. Ecco una sezione del file xml:xmlns namespace breaking lxml

<?xml version='1.0' encoding='UTF-8'?> 
<package xmlns="http://apple.com/itunes/importer" version="film4.7"> 
    <provider>filmgroup</provider> 
    <language>en-GB</language> 
    <actor name="John Smith" display="Doe John"</actor> 
</package> 

Ed ecco un esempio del mio codice Python:

metadata = '/Users/mylaptop/Desktop/Python/metadata.xml' 
from lxml import etree 
parser = etree.XMLParser(remove_blank_text=True) 
open(metadata) 
tree = etree.parse(metadata, parser) 
root = tree.getroot() 
for element in root.iter(tag='provider'): 
    providerValue = tree.find('//provider') 
    providerValue = providerValue.text 
    print providerValue 
tree.write('/Users/mylaptop/Desktop/Python/metadataDone.xml', pretty_print = True, xml_declaration = True, encoding = 'UTF-8') 

Quando ho eseguito questo non è possibile trovare il tag fornitore o il suo valore. Se rimuovo xmlns="http://apple.com/itunes/importer" allora tutto funziona come previsto. La mia domanda è come posso rimuovere questo spazio dei nomi, perché non sono affatto interessato a questo, quindi posso ottenere i valori dei tag che ho bisogno di usare lxml?

risposta

9

Il provider tag è nel http://apple.com/itunes/importer spazio dei nomi, in modo che sia necessario utilizzare il nome completo

{http://apple.com/itunes/importer}provider 

o utilizzare uno dei metodi lxml che ha the namespaces parameter, come root.xpath. Poi è possibile specificare con un prefisso dello spazio dei nomi (per esempio ns:provider):

from lxml import etree 
parser = etree.XMLParser(remove_blank_text=True) 
tree = etree.parse(metadata, parser) 
root = tree.getroot() 
namespaces = {'ns':'http://apple.com/itunes/importer'} 
items = iter(root.xpath('//ns:provider/text()|//ns:actor/@name', 
         namespaces=namespaces)) 
for provider, actor in zip(*[items]*2): 
    print(provider, actor) 

rendimenti

('filmgroup', 'John Smith') 

notare che il XPath utilizzato sopra presuppone che <provider> e <actor> elementi appaiono sempre in alternanza. Se questo non è vero, allora ci sono naturalmente modi per gestire, ma il codice diventa un po 'più dettagliato:

for package in root.xpath('//ns:package', namespaces=namespaces): 
    for provider in package.xpath('ns:provider', namespaces=namespaces): 
     providerValue = provider.text 
     print providerValue 
    for actor in package.xpath('ns:actor', namespaces=namespaces): 
     print actor.attrib['name'] 
+0

Quello è eccellente ubuntu, funziona a meraviglia, applausi. – speedyrazor

+0

ubuntu, come trovo un attributo di un tag, ho ammesso il mio esempio originale, quindi sto cercando il valore del nome dell'attore = – speedyrazor

+0

Se si ha l'elemento ', è possibile accedere al valore dell'attributo con l'elemento' .attrib [ 'name'] '. Tuttavia, se si stanno rasando gli elementi 'provider' e' actor' da un file XML, è possibile impostare un singolo XPath per eseguire entrambi contemporaneamente la sintassi '|' (o). Ho modificato il post per mostrare cosa intendo. – unutbu

1

Il mio suggerimento è di non ignorare lo spazio dei nomi, ma, invece, di prendere in considerazione. Ho scritto alcune funzioni correlate (copiate con lievi modifiche) per il mio lavoro sulla libreria django-quickbooks. Con queste funzioni, si dovrebbe essere in grado di fare questo:

providers = getels(root, 'provider', ns='http://apple.com/itunes/importer') 

Qui ci sono quelle funzioni:

def get_tag_with_ns(tag_name, ns): 
    return '{%s}%s' % (ns, tag_name) 

def getel(elt, tag_name, ns=None): 
    """ Gets the first tag that matches the specified tag_name taking into 
    account the QB namespace. 

    :param ns: The namespace to use if not using the default one for 
    django-quickbooks. 
    :type ns: string 
    """ 

    res = elt.find(get_tag_with_ns(tag_name, ns=ns)) 
    if res is None: 
     raise TagNotFound('Could not find tag by name "%s"' % tag_name) 
    return res 

def getels(elt, *path, **kwargs): 
    """ Gets the first set of elements found at the specified path. 

    Example: 
     >>> xml = (
     "<root>" + 
      "<item>" + 
       "<id>1</id>" + 
      "</item>" + 
      "<item>" + 
       "<id>2</id>"* + 
      "</item>" + 
     "</root>") 
     >>> el = etree.fromstring(xml) 
     >>> getels(el, 'root', 'item', ns='correct/namespace') 
     [<Element item>, <Element item>] 
    """ 

    ns = kwargs['ns'] 

    i=-1 
    for i in range(len(path)-1): 
     elt = getel(elt, path[i], ns=ns) 
    tag_name = path[i+1] 
    return elt.findall(get_tag_with_ns(tag_name, ns=ns))