2017-02-06 32 views
0

PythonでXMLをナビゲートする最も簡単な方法は何ですか?XMLを反復処理しますか?

<html> 
<body> 
    <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <soapenv:body> 
    <getservicebyidresponse xmlns="http://www.something.com/soa/2.0/SRIManagement"> 
    <code xmlns=""> 
     0 
    </code> 
    <client xmlns=""> 
     <action xsi:nil="true"> 
     </action> 
     <actionmode xsi:nil="true"> 
     </actionmode> 
     <clientid> 
     405965216 
     </clientid> 
     <firstname xsi:nil="true"> 
     </firstname> 
     <id xsi:nil="true"> 
     </id> 
     <lastname> 
     Last Name 
     </lastname> 
     <role xsi:nil="true"> 
     </role> 
     <state xsi:nil="true"> 
     </state> 
    </client> 
    </getservicebyidresponse> 
    </soapenv:body> 
    </soapenv:envelope> 
</body> 
</html> 

私は正規表現に行き、私が必要とする行の値を取得しようとしますが、pythonの方法はありますか? xml[0][1]などのようなもの?

+1

https://docs.python.org/3/library/xml.etree.elementtree.html – deceze

+2

@brunodesthuilliersは必要に応じて複製としてマークします。だからGoogleに教えてはいけません。 [再帰的にElementTreeのを使用してPythonでXMLタグを反復処理する方法?]の –

+0

可能な複製(http://stackoverflow.com/questions/21074361/how-to-recursively-iterate-over-xml-tags-in-python-using [ERRNO 36]長すぎるファイル名:-elementtree) –

答えて

2

@decezeはすでに指摘されているので、ここではxml.etree.ElementTreeを使用できます。

import xml.etree.ElementTree as ET 
tree = ET.parse("path_to_xml_file") 
root = tree.getroot() 

あなたは、ルートのすべての子ノードを反復処理することができます

for child in root.iter(): 
    if child.tag == 'clientid': 
     print child.tag, child.text.strip() 

子供が入れ子になっている、と私たちは、インデックスによって特定の子ノードにアクセスすることができますので、root[0][1]は限りインデックスが正しいと(動作するはずです)。

+0

これは私が '例外IOErrorが与える' –

+0

は親切にこの回答を参照してください - http://stackoverflow.com/a/29891397/2689986。 ファイル名を 'ET.parse'関数に渡すのではなく、ファイルの内容を渡している可能性があります。 –

+1

これで 'root = ET.fromstring(xml)'がこれを修正しました。XMLファイル –