2017-05-30 2 views
0

は、私はここで、「フォルダ」の要素このkmlファイルのフォルダ要素のリストを返すにはどうすればいいですか?ここ

を抽出したいファイルの先頭

<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="http://www.opengis.net/kml/2.2"> 
    <Document> 
    <Folder> 
    <name>Points</name> 
    <Placemark> 
    <name>Port Saeed, Dubai</name> 
    <styleUrl>#icon-1899-0288D1-nodesc</styleUrl> 
    <Point> 
     <coordinates> 
     55.3295568,25.2513145,0 
     </coordinates> 
    </Point> 
    </Placemark> 
    <Placemark> 
    <name>Retail Location #1</name> 
    <description>Paris, France</description> 
    <styleUrl>#icon-1899-0288D1</styleUrl> 
    <Point> 
     <coordinates> 
     2.3620605,48.8867304,0 
     </coordinates> 
    </Point> 
    </Placemark> 
    <Placemark> 
    <name>Odessa Oblast</name> 
... 

である私のコードです。

tree = ET.parse(kml) 
root = tree.getroot() 

for element in root: 
    print element.findall('.//{http://www.opengis.net/kml/2.2/}Folder') 

これは、[]を今すぐ印刷します。私はその名前空間に関する問題を信じています。私はその文字列を作成する方法を理解できませんか?また、xpathを代わりに使う価値があるでしょうか?私は名前空間にも同じ問題があると思います。

+0

*フォルダ*は、終了タグを持っていますか? – Parfait

+0

ええ、申し訳ありませんが、私はそれが長すぎるようにファイル全体を貼り付けていませんでした – BigBoy1337

答えて

1

の子孫全体を反復することを検討してください。このノードには子要素と孫要素が含まれています。また、解析に使用する名前空間の接頭辞は、スラッシュで終わってはいけません。ネストされたリストについては

import xml.etree.ElementTree as ET 

root = ET.fromstring('''<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="http://www.opengis.net/kml/2.2"> 
    <Document> 
    <Folder> 
     <name>Points</name> 
     <Placemark> 
     <name>Port Saeed, Dubai</name> 
     <styleUrl>#icon-1899-0288D1-nodesc</styleUrl> 
     <Point> 
      <coordinates> 
     55.3295568,25.2513145,0 
      </coordinates> 
     </Point> 
     </Placemark> 
     <Placemark> 
     <name>Retail Location #1</name> 
     <description>Paris, France</description> 
     <styleUrl>#icon-1899-0288D1</styleUrl> 
     <Point> 
      <coordinates> 
     2.3620605,48.8867304,0 
      </coordinates> 
     </Point> 
     </Placemark> 
    </Folder> 
    </Document> 
</kml>''') 

# FIND ALL FOLDERS 
for i in root.findall('.//{http://www.opengis.net/kml/2.2}Folder'): 
    # FIND ALL FOLDER'S DESCENDANTS 
    for inner in i.findall('.//*'): 
     data = inner.text.strip()  # STRIP LEAD/TRAIL WHITESPACE 
     if len(data) > 1:    # LEAVE OUT EMPTY ELEMENTS 
      print(data) 

# Points 
# Port Saeed, Dubai 
# icon-1899-0288D1-nodesc 
# 55.3295568,25.2513145,0 
# Retail Location #1 
# Paris, France 
# #icon-1899-0288D1 
# 2.3620605,48.8867304,0 

、各内側のリストは、各フォルダに対応リストにノードのテキストを追加:

data = [] 
for i in root.findall('.//{http://www.opengis.net/kml/2.2}Folder'): 
    inner = [] 
    for t in i.findall('.//*'): 
     txt = t.text.strip() 
     if len(txt) > 1: 
      inner.append(txt) 

    data.append(inner) 
関連する問題