gpt4 book ai didi

python - 使用 Python 的 XPATH 解析 XML

转载 作者:行者123 更新时间:2023-12-02 03:08:27 27 4
gpt4 key购买 nike

我是 Python 新手 - 才几天 - 我希望得到一些帮助。

我想编写一个 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>

最佳答案

首先,您生成的 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'))

希望有帮助,

关于python - 使用 Python 的 XPATH 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27247549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com