2014-12-02 100 views
0

我是Python新手 - 幾天前 - 我希望得到一些幫助。爲Python解析XML使用XPATH

我想編寫一個Python代碼來解析如下下面的XML: -

ServingCell ---------- NeighbourCell
L41_NBR3347_1 ---------- L41_NBR3347_2
L41_NBR3347_1 ---------- L41_NBR3347_3
L41_NBR3347_1 ---------- L41_NBR3349_1
L41_NBR3347_1 ---------- L41_NBREA2242_1

<LteCell id="L41_NBR3347_1"> 
<attributes> 
    <absPatternInfoTdd><unset/></absPatternInfoTdd> 
    <additionalSpectrumEmission>1</additionalSpectrumEmission> 
    <additionalSpectrumEmissionList><unset/></additionalSpectrumEmissionList> 
    <LteSpeedDependentConf id="0">     
    <attributes>          
    <tReselectionEutraSfHigh>lDot0</tReselectionEut 
    <tReselectionEutraSfMedium>lDot0</tReselectionE 
    </attributes>         
    </LteSpeedDependentConf>       
    <LteNeighboringCellRelation id="L41_NBR3347_2"> 
    <attributes>          
    <absPatternInfo><unset/></absPatternInfo>  
    </LteNeighboringCellRelation>      
    <LteNeighboringCellRelation id="L41_NBR3347_3"> 
    <attributes>          
    <absPatternInfo><unset/></absPatternInfo>  
    </LteNeighboringCellRelation>      
    <LteNeighboringCellRelation id="L41_NBR3349_1"> 
    <attributes>          
    <absPatternInfo><unset/></absPatternInfo>        
    </LteNeighboringCellRelation>      
    <LteNeighboringCellRelation id="L41_NBREA2242_1"> 
    <attributes>          
    <absPatternInfo><unset/></absPatternInfo>  
    <absPatternInfoTdd><unset/></absPatternInfoTdd> 
+0

查找BS4或LXML – 2014-12-02 12:02:59

回答

0

首先,您製作的xml路徑不正確:您需要關閉打開的標籤。 例如屬性已打開且未關閉。

<LteNeighboringCellRelation id="L41_NBR3349_1"> 
     <attributes>          
     <absPatternInfo> 
      <unset/> 
     </absPatternInfo>        
    </LteNeighboringCellRelation> 

我重構(並簡化了一點點)的XML來糾正它。

<LteCell id="L41_NBR3347_1"> 
    <attributes>      
     <LteNeighboringCellRelation id="L41_NBR3347_2">           
     </LteNeighboringCellRelation>      
     <LteNeighboringCellRelation id="L41_NBR3347_3">   
     </LteNeighboringCellRelation>      
     <LteNeighboringCellRelation id="L41_NBR3349_1">                
     </LteNeighboringCellRelation>      
     <LteNeighboringCellRelation id="L41_NBREA2242_1"> 
     </LteNeighboringCellRelation> 
    </attributes> 
</LteCell> 

這是解析和顯示它的代碼。

import xml.etree.ElementTree as ET 
tree = ET.parse("XmlExample.xml") 
result = '' 
root = tree.getroot() 

for e in tree.findall('./attributes/LteNeighboringCellRelation'):#attributes/LteNeighboringCellRelation 
    print(root.attrib['id']+'----------'+e.attrib.get('id')) 

希望幫助,