如何使用python获取xml的值?

时间:2017-10-27 22:10:15

标签: python xml

我有一个像这样的xml文件:

<component apiversion="" class="BSP" condition="" group="Board" subgroup="s7g2_sk" variant="" vendor="balabala" version="1.1.1.1">
      <description>SK Board Support Files</description>
      <originalPack>board_s7g2_sk.1.3.0.pack</originalPack>
    </component>

我想提取子组值:s7g2_sk,我该怎么做?

感谢。

2 个答案:

答案 0 :(得分:1)

lxml库可以轻松完成此任务:

from lxml import etree

xml="""    
<component apiversion="" class="BSP" condition="" group="Board" subgroup="s7g2_sk" variant="" vendor="balabala" version="1.1.1.1">
      <description>SK Board Support Files</description>
      <originalPack>board_s7g2_sk.1.3.0.pack</originalPack>
    </component>    
"""

root = etree.fromstring(xml)
print(root.get('subgroup'))
#>>> s7g2_sk

答案 1 :(得分:0)

或者,假设一个名为test.xml的可访问文件:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print(root.attrib['subgroup']) # s7g2_sk