[英]Parsing XML Using XPATH for Python
I am new to Python - a few days old - and I would appreciate some help. 我是Python的新手-刚成立几天-希望获得一些帮助。
I want write a python code to parse the below XML as below:- 我想编写一个python代码来解析以下XML,如下所示:
ServingCell----------NeighbourCell ServingCell ---------- NeighbourCell
L41_NBR3347_1----------L41_NBR3347_2 L41_NBR3347_1 ---------- L41_NBR3347_2
L41_NBR3347_1----------L41_NBR3347_3 L41_NBR3347_1 ---------- L41_NBR3347_3
L41_NBR3347_1----------L41_NBR3349_1 L41_NBR3347_1 ---------- L41_NBR3349_1
L41_NBR3347_1----------L41_NBREA2242_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>
First the xml path you produced is not correct: you need to close the tags your open. 首先,您生成的xml路径不正确:您需要关闭打开的标签。 For example attributes is opened and not closed. 例如, 属性是打开的而不是关闭的。
<LteNeighboringCellRelation id="L41_NBR3349_1">
<attributes>
<absPatternInfo>
<unset/>
</absPatternInfo>
</LteNeighboringCellRelation>
I refactored (and simplified it a little bit) the xml to correct it. 我重构(并简化了一点)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>
Here is the code to parse and display it. 这是要解析和显示的代码。
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'))
Hope that helps, 希望能有所帮助,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.