2012-09-12 33 views
0

的xmlns文字我有這樣的XML:我怎麼能找到與ElementTree的

<office:body> 
<office:text> 
<text:sequence-decls> 
<text:sequence-decl text:display-outline-level="0" text:name="Illustration"/> 
<text:sequence-decl text:display-outline-level="0" text:name="Table"/> 
<text:sequence-decl text:display-outline-level="0" text:name="Text"/> 
<text:sequence-decl text:display-outline-level="0" text:name="Drawing"/> 
</text:sequence-decls> 
<text:p text:style-name="Standard"> 
<office:annotation>...</office:annotation> 
foobar 
</text:p> 
</office:text> 
</office:body> 

我想找到文本「foobar的」與ElementTree的因爲不是「FOOBAR」可以是任何文字?

回答

1

假設XML文檔看起來像這樣(與聲明的名稱空間):

<office:document-content xmlns:office="http://openoffice.org/2000/office" 
         xmlns:text="http://openoffice.org/2000/text"> 

    <office:body> 
    <office:text> 
     <text:sequence-decls> 
     <text:sequence-decl text:display-outline-level="0" text:name="Illustration"/> 
     <text:sequence-decl text:display-outline-level="0" text:name="Table"/> 
     <text:sequence-decl text:display-outline-level="0" text:name="Text"/> 
     <text:sequence-decl text:display-outline-level="0" text:name="Drawing"/> 
     </text:sequence-decls> 
     <text:p text:style-name="Standard"> 
     <office:annotation>...</office:annotation> 
     foobar 
     </text:p> 
    </office:text> 
    </office:body> 

</office:document-content> 

然後,您可以使用該程序獲得 「FOOBAR」 字符串:

from xml.etree import ElementTree as ET 

root = ET.parse("foobar.xml") 
ann = root.find(".//{http://openoffice.org/2000/office}annotation") 
print ann.tail.strip() 

這裏,ElementTree.find()方法用於查找office:annotation元素,Element.tail屬性返回元素結束標記後的文本內容。