2012-03-31 11 views
0

私はdom.minidom関数を使用してXMLの一部を抽出する方法を学習しており、特定の要素と属性を正常に返すことができます。PythonでXMLを「歩く」ための正式な方法はありますか?

私に解析したい大量のXMLファイルがあり、すべての結果をdbにプッシュします。 os.walkのような、階層構造を保持する論理的な方法でXMLから要素を抽出して抽出する機能がありますか?

XMLはかなり基本的であり、非常に単純です:(この小さな例では)XMLとクロール各特定InternalSignatureに関連する要素を抽出する正式な方法は

<InternalSignature ID="9" Specificity="Generic"> 
<ByteSequence Reference="BOFoffset"> 
    <SubSequence Position="1" SubSeqMinOffset="0" SubSeqMaxOffset="0" MinFragLength="0"> 
    <Sequence>49492A00</Sequence> 
    <DefaultShift>5</DefaultShift> 
    <Shift Byte="00">1</Shift> 
    <Shift Byte="2A">2</Shift> 
    <Shift Byte="49">3</Shift> 
    </SubSequence> 
</ByteSequence> 
</InternalSignature> 
<InternalSignature ID="10" Specificity="Generic"> 
<ByteSequence Reference="BOFoffset"> 
    <SubSequence Position="1" SubSeqMinOffset="0" SubSeqMaxOffset="0" MinFragLength="0"> 
    <Sequence>4D4D002A</Sequence> 
    <DefaultShift>5</DefaultShift> 
    <Shift Byte="2A">1</Shift> 
    <Shift Byte="00">2</Shift> 
    <Shift Byte="4D">3</Shift> 
    </SubSequence> 
</ByteSequence> 
</InternalSignature> 

ありますか? minidom.parseと.GetElementsByNameメソッドを使ってリストを介して物事を呼び出す方法を見ることができますが、要素を階層表現にどのように関連付けるかはわかりません。私はInternalSignatureList 134個の要素があることを最後の行(LEN)から見ることができ、かつ、本質的に私がしたい

xmldoc = minidom.parse("file.xml") 
Versionlist = xmldoc.getElementsByTagName('FFSignatureFile') 
VersionRef = Versionlist[0] 
Version = VersionRef.attributes["Version"] 
DateCreated = VersionRef.attributes["DateCreated"] 
print Version.value 
print DateCreated.value 
InternalSignatureList = xmldoc.getElementsByTagName('InternalSignature') 
InternalSignatureRef = InternalSignatureList[0] 
SigID = InternalSignatureRef.attributes["ID"] 
SigSpecificity = InternalSignatureRef.attributes["Specificity"] 
print SigID.value 
print SigSpecificity.value 
print len(InternalSignatureList) 

これまでのところ私は、様々な値を返す方法を示してチュートリアルを発見しました個々のレコードとして各InternalSignature内のすべての要素を抽出し、それをdbにフリックすることができます。

+0

うーん、私は質問を理解している場合はわからないが、方法については、[XPathの](http://en.wikipedia.org/wiki/XPath) ( 'getchildren()'と組み合わせることが可能です - 少なくとも 'lxml'はXMLツリーをトラバースするためにXMLを使用することをサポートしています – Kimvais

答えて

3

(あなたは試してみましたか?)

from xml.etree import ElementTree 

e = ElementTree.fromstring(xmlstring) 
e.findall("ByteSequence") 
+0

うわー、Googleでこれを見つけました。 – Glycerine

関連する問題