2017-04-25 20 views
0

私は以下のようなXMLを持っています。minidomを使ってPythonでXMLを解析する

<root> 
<entry> 
    <accession>A</accession> 
    <accession>B</accession> 
    <accession>C</accession> 
    <feature type="cross-link" description="sumo2"> 
     <location> 
      <position position="15111992"/> 
     </location> 
    </feature> 
    <feature type="temp" description="blah blah sumo"> 
     <location> 
      <position position="12345"/> 
     </location> 
    </feature> 
</entry> 
<entry> 
    <accession>X</accession> 
    <accession>Y</accession> 
    <accession>Z</accession> 
    <feature type="test" description="testing"> 
     <location> 
      <position position="1"/> 
     </location> 
    </feature> 
    <feature type="cross-link" description="sumo hello"> 
     <location> 
      <position position="11223344"/> 
     </location> 
    </feature> 
</entry> 
</root> 

機能タイプが「クロスリンク」で、説明に単語sumoが含まれているposiiton属性の値を取得する必要があります。 これは、私がこれまでに試したことですが、フィーチャタイプが "クロスリンク"であり、説明にsumoという単語が含まれている値を正しく提供しています。私は言葉「相撲」を含むフィーチャ「クロスリンク」などの種類と説明をしたら

from xml.dom import minidom 
xmldoc = minidom.parse('P38398.xml') 
itemlist = xmldoc.getElementsByTagName('feature') 

for s in itemlist: 
    feattype = s.attributes['type'].value 
    description = s.attributes['description'].value 
    if "SUMO" in description: 
     if "cross-link" in feattype: 
      print feattype+","+description 

は、どのように私は位置の値を抽出することができますか?

答えて

0

あなたは二つの点を除いてほとんどがあります:あなたは、その後に次のようなものを追加する必要が

  • 上に与えられたデータと一致するように小文字にあなたの「相撲」の検索パターンを変更する必要が

    • あなたのループ本体

      posList = s.getElementsByTagName('position') 
      for p in posList: 
          print "-- position is {}".format(p.attributes['position'].value) 
      
  • +0

    ありがとうございました。 – Ghauri

    0

    これは、XPathのための仕事です。 attribute matchessubstring matchesの単純なチェックを行い、属性を文字列として返します。

    from lxml import etree 
    root = etree.parse('P38398.xml').getroot() 
    xpquery = '//feature[@type="cross-link" and contains(@description, "sumo")]//position/@position' 
    for att in root.xpath(xpquery): 
        print(att) 
    
    関連する問題