2015-04-06 53 views
0

我試圖解析格式獲取XML孩子的名字,以及他們與子女LXML只返回無

<?xml version="1.0" encoding="utf-8"?> 
<ttFont sfntVersion="OTTO" ttLibVersion="2.5"> 

    <cmap> 
    <tableVersion version="0"/> 
    <cmap_format_4 platformID="0" platEncID="3" language="0"> 
     <map code="0x0" name=".null"/><!-- ???? --> 
     <map code="0xd" name="CR"/><!-- ???? --> 

基礎教程here使用LXML一些XML,但由於某些原因,簡單的命令

xmlFileName = "xml/myfile.ttx" 
f = open(xmlFileName, "r") 
s = f.read() 

doc = etree.XML(s.strip()) 
map = doc.findtext('map') 
print map 

只返回None。我如何獲得所有cmap的孩子(例如,cmap_format_4)和所有地圖孩子的節點名稱?

+0

''findtext''將只在第一時間發現了''map'' ** **文本出現。從你的例子來看,你沒有地圖作爲文本/內容。如果你正在尋找地圖在元素的標籤,然後使用''find''或''findall'' –

回答

0

使用findall()可獲得cmap_format_4節點的所有map子節點。例如:

for cmap_format in doc.findall('.//cmap_format_4'): 
    for m in cmap_format.findall('map'): 
     print m.attrib['code'] 

打印:

0x0 
0xd 
+0

非常感謝。我怎樣才能用這個變量(和未知名稱)的數量'cmap_format_N'節點?我想遍歷每個「地圖」節點,但是可以一路訪問父母的姓名。 – 1252748

+0

另外,我在doc.findall('.//cmap_format_4/map')中得到m的錯誤: AttributeError:'file'對象沒有屬性'findall'。我用'xmlFileName =「xml/BeretLTStd-Bold.ttx」'[new line]'doc = open(xmlFileName,「r」)'得到我的XML。我應該以其他方式做嗎?再次感謝。 – 1252748

+0

@thomas'doc'是'etree.parse()'調用的結果。 – alecxe