2012-01-13 33 views

Trả lời

2

Bạn không thể thay thế một phần tử từ ElementTree bạn chỉ có thể làm việc với Element.

Ngay cả khi bạn gọi ElementTree.find(), đó chỉ là phím tắt cho getroot().find().

Vì vậy, bạn thực sự cần phải:

  • trích xuất các yếu tố phụ huynh
  • sử dụng sự hiểu biết (hoặc bất cứ điều gì bạn muốn) trên đó yếu tố phụ huynh

Việc khai thác các yếu tố phụ huynh có thể dễ dàng nếu mục tiêu của bạn là một phần tử con gốc (chỉ cần gọi getroot()) nếu không bạn sẽ phải tìm nó.

2

Không giống như DOM, etree không có chức năng đa tài liệu rõ ràng. Tuy nhiên, bạn chỉ có thể di chuyển các phần tử một cách tự do từ tài liệu này sang tài liệu khác. Bạn có thể gọi tới số _setroot sau khi làm như vậy.

Bằng cách gọi insert và sau đó remove, bạn có thể thay thế nút trong tài liệu.

1

Tôi mới để trăn, nhưng tôi đã tìm ra một cách tinh ranh để làm điều này:

Input tập tin input1.xml:

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

tập tin đầu vào input2.xml:

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

Python mã: (lưu ý, lộn xộn và 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) 

cho kết quả:

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

này đã được ký kết với thông tin từ:

Các vấn đề liên quan