首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python中迭代子标记的XML子标记

在Python中迭代子标记的XML子标记
EN

Stack Overflow用户
提问于 2015-07-14 23:36:00
回答 1查看 1.2K关注 0票数 0

目前,我有一个XML文件。我想说,如果string是this,则打印与this关联的所有子元素。我已经记录了一些我尝试过的代码。我在使用内置的元素树。

XML

代码语言:javascript
运行
复制
<commands>
    <command name="this" type="out" major="0x1" minor="0x0">
        <data bytes="1-0" descrip=" ID"></data>
        <data bytes="3-2" descrip=" ID"></data>
        <data bytes="5-4" descrip=" ID"></data>
        <data bytes="7-6" descrip="  Code"></data>
        <data bytes="12-8" descrip=" Revision"></data>
        <data bytes="13" descrip=" Version"></data>
        <data bytes="14" descrip="   Mask"></data>
        <data bytes="15" descrip="Reserved"></data>
        <data bytes="17-16" descrip="   Windows"></data>
        <data bytes="19-18" descrip=" of Write Flush Addresses"></data>
    </command>
</commands>

示例代码以解析名称

代码语言:javascript
运行
复制
tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])

基本上,我想深入一点,打印命令名的子标签。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-14 23:51:29

你必须得到孩子的孩子,并且遍历所有的孙辈。

代码语言:javascript
运行
复制
tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])    
        for grandchild in child.getchildren():
            print str(grandchild.attrib['bytes'])
            print str(grandchild.attrib['descrip'])

或者,如果要打印完整的XML行,可以这样做:

代码语言:javascript
运行
复制
print ET.tostring(grandchild).strip()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31419156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档