2014-11-22 2 views
1

XML 파일에서 노드를 삭제하려고합니다. 나는 그걸 멀리 할 수 ​​있었지만 스크립트가 실행될 때 부모 요소에 속한 속성을 가져 오는 것으로 보입니다. 여기 요소의 꼬리에서 내용을 제거하지 않고 XML 요소를 제거하려면 어떻게해야합니까?

코드입니다 :

for i, pid in enumerate(root.findall(".//p")): 
    for cont in pid.findall('membercontribution'): 
      for col in cont.findall('col'): 
       cont.remove(col) 


tree.write('fofo.xml') 

이 :

<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)  
</member><membercontribution>: a policy </membercontribution></p> 

내가 "는 foobar의 barforb을 계속받을 수 있도록 내가이 코드를 어떻게 :

<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten)   
</member><membercontribution>: a policy 
<col>16</col> 
foobar barforb </membercontribution></p> 

이된다 "그 다음에 오는 부분?

답변

1

여기서 실수로 제거되는 것은 속성이 아니며 요소의 내용 (tail)입니다.

tail 속성은 ElementTree API의 고유 한 특성입니다. 요소의 종료 태그 바로 뒤에 있고 다른 태그 앞에 오는 텍스트입니다. 요소 (이 경우 col)를 제거하면 꼬리도 제거됩니다.

제가 발견 한 가장 명확한 설명은 http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html입니다.


가 원하는 결과를 얻으려면, 당신은 제거 col 요소의 꼬리에 대한 참조를 유지하고 부모 요소의 텍스트에 추가해야합니다. 완전한 예 :

from xml.etree import ElementTree as ET 

XML = """ 
<root> 
<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten) 
</member><membercontribution>: a policy 
<col>16</col> 
foobar barforb </membercontribution></p> 
</root> 
""" 

root = ET.fromstring(XML) 

for pid in root.findall(".//p"): 
    for cont in pid.findall('membercontribution'): 
     for col in cont.findall('col'): 
      col_tail = col.tail.strip()   # Get the tail of "col" 
      cont.remove(col)      # Remove "col" 
      cont.text = cont.text.strip() + " " # Replace trailing whitespace with single space 
      cont.text = cont.text + col_tail  # Add the tail to "membercontribution" 

print ET.tostring(root) 

출력 : 이것에 대한

<root> 
<p id="S6CV0001P0-00507"><member>The Minister for Overseas Development (Mr. Neil Marten) 
</member><membercontribution>: a policy foobar barforb</membercontribution></p> 
</root> 
+0

감사합니다. "policy"와 "foobar"사이에 나타나는 줄 바꿈을 제거 할 수있는 방법이 있습니까? –

관련 문제