python - 使用xml打印子节点

标签 python xml-parsing

这是我正在使用的 api xml:

<response>
    <request>polaris</request>
    <status>0</status>
    <verbiage>OK</verbiage>
    <object id="S251">
        <type id="1">Star</type>
        <name>α UMi</name>
        <catId>α UMi</catId>
        <constellation id="84">Ursa Minor</constellation>
        <ra unit="hour">2.5301944</ra>
        <de unit="degree">89.264167</de>
        <mag>2.02</mag>
    </object>
    <object id="S251">
        <type id="1">Star</type>
        <name>α UMi</name>
        <catId>α UMi</catId>
        <constellation id="84">Ursa Minor</constellation>
        <ra unit="hour">2.5301944</ra>
        <de unit="degree">89.264167</de>
        <mag>2.02</mag>
    </object>
</response>

这是我当前的代码:

   #!/usr/bin/env python

   import xml.etree.ElementTree as ET
   tree = ET.parse('StarGaze.xml')
   root = tree.getroot()
   callevent=root.find('polaris')

   Moc1=callevent.find('polaris')


   for node in Moc1.getiterator():
       if node.tag=='constellation id':
           print node.tag, node.attrib, node.text'

我希望能够打印定义的子项。例如:

星座id=

ra 单位=

任何帮助将不胜感激

最佳答案

迭代object节点并使用findall()定位constellationra节点>find() 方法和 .attrib 属性:

import xml.etree.ElementTree as ET

tree = ET.parse('StarGaze.xml')
root = tree.getroot()

for obj in root.findall("object"):
    constellation = obj.find("constellation")
    ra = obj.find("ra")

    print(constellation.attrib["id"], constellation.text, ra.attrib["unit"], ra.text)

将打印:

84 Ursa Minor hour 2.5301944
84 Ursa Minor hour 2.5301944

关于python - 使用xml打印子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602047/

相关文章:

python - 我可以只对更改的代码执行静态分析吗?

python - Python如何使用numpy数组进行垃圾回收追加和删除?

c - PugiXML 值输出编码

java - 无法获取 xml 文件中名称为 ="debitRequest"的父节点的子节点名称

python - Nullable DecimalField 在空白时返回 'This value must be a decimal number'

python - 如何批量拆分numpy数组?

python - 类型错误 : 'Keyword argument not understood:' , 'padding'

ios - 如何解析我添加到项目中的 XML 文件

node.js - AWS Lambda 函数中的 XML 解析

sql - 遍历 XML 节点并在 SQL Server 中发送电子邮件