2012-01-13 17 views

Respuesta

2

No puede reemplazar un elemento del ElementTree, solo puede trabajar con Element.

Incluso cuando llame al ElementTree.find() es solo un atajo para getroot().find().

Por lo que realmente necesitan:

  • extraer el elemento padre
  • uso comprensión (o lo que quieras) en ese elemento padre

La extracción del elemento padre puede ser fácil si su objetivo es un subelemento raíz (solo llame al getroot()), de lo contrario, tendrá que encontrarlo.

2

A diferencia del DOM, etree no tiene funciones explícitas de múltiples documentos. Sin embargo, debería poder mover elementos libremente de un documento a otro. Es posible que desee llamar al _setroot después de hacerlo.

Llamando insert y luego remove, puede reemplazar un nodo en un documento.

1

Soy nuevo en Python, pero he encontrado una manera poco fiable para hacer esto:

Archivo de entrada input1.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <import ref="input2.xml" /> 
    <name awesome="true">Chuck</name> 
</root> 

Archivo de entrada input2.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<foo> 
    <bar>blah blah</bar> 
</foo> 

Python código: (nota, desordenado y hacky)

import os 
import xml.etree.ElementTree as ElementTree 

def getElementTree(xmlFile): 
    print "-- Processing file: '%s' in: '%s'" %(xmlFile, os.getcwd()) 
    xmlFH = open(xmlFile, 'r') 
    xmlStr = xmlFH.read() 
    et = ElementTree.fromstring(xmlStr) 
    parent_map = dict((c, p) for p in et.getiterator() for c in p) 
    # ref: https://stackoverflow.com/questions/2170610/access-elementtree-node-parent-node/2170994 
    importList = et.findall('.//import[@ref]') 
    for importPlaceholder in importList: 
     old_dir = os.getcwd() 
     new_dir = os.path.dirname(importPlaceholder.attrib['ref']) 
     shallPushd = os.path.exists(new_dir) 
     if shallPushd: 
      print " pushd: %s" %(new_dir) 
      os.chdir(new_dir) # pushd (for relative linking) 
     # Recursing to import element from file reference 
     importedElement = getElementTree(os.path.basename(importPlaceholder.attrib['ref'])) 

     # element replacement 
     parent = parent_map[importPlaceholder] 
     index = parent._children.index(importPlaceholder) 
     parent._children[index] = importedElement 

     if shallPushd: 
      print " popd: %s" %(old_dir) 
      os.chdir(old_dir) # popd 

    return et 

xmlET = getElementTree("input1.xml") 
print ElementTree.tostring(xmlET) 

da la salida:

-- Processing file: 'input1.xml' in: 'C:\temp\testing' 
-- Processing file: 'input2.xml' in: 'C:\temp\testing' 
<root> 
    <foo> 
    <bar>blah blah</bar> 
</foo><name awesome="true">Chuck</name> 
</root> 

esto se concluyó con información de:

Cuestiones relacionadas