Как получить отдельные элементы в теге xml в python из - PullRequest
0 голосов
/ 23 октября 2019
  1. Элемент списка

[введите описание изображения здесь] [1].

Как получить значения отдельно regname, введите ... в python. Мне нужно отдельно получить значение типа и addr.

    for regfile in root.findall('regfile'):
        reg_value = regfile.find('reg').text
        print(reg_value)
        for reg in regfile.findall('reg'):
            name = reg.find('name').text
            type = reg.find('text').text

Я пытался, но выдает ошибку вроде "AttributeError: у объекта 'NoneType' нет атрибута 'text'"

    <regfile regfilename="blkreq" type="blk_required_v2_rdl_rf_t" num="1" addr="0x0" incr="0x8">
        <name><![CDATA[blk_required_v2_rdl_rf_t]]></name>
        <description><![CDATA[]]></description>
        <property name="num" value="1"/>
        <reg regname="uid_v2" type="block_uid_v2_t" num="1" addr="0x4" incr="0x4">
            <name><![CDATA[Block Unique ID Type]]></name>
            <description><![CDATA[The IPID and the Platform Type together provides Unique ID of an IP]]></description>
            <property name="msbhigh" value="1"/>
            <property name="num" value="1"/>
            <property name="retention" value=""/>
            <property name="width" value="32"/>
            <property name="shared" value="0"/>
            <property name="accesswidth" value="8"/>
            <field fieldname="ipid">
                <name><![CDATA[Design IP Identification]]></name>
                <description><![CDATA[This is reserved for future use.]]></description>
                <msb>31</msb>
                <lsb>8</lsb>
                <property name="hw_r" value="1"/>
                <property name="reset" value="0h"/>
                <property name="retention" value=""/>
                <property name="sw_r" value="1"/>
                <property name="width" value="0"/>
            </field>
            <field fieldname="platform">
                <name><![CDATA[Platform]]></name>
                <description><![CDATA[Implementation for the specific platform class (asic, fpga, vp, etc) - supplied 
           a global parameter, PLATFORM_TYPE, by the RTL and defined in the platform package in DVI_LIB. 
           The reset value shall reflect the configuration.]]></description>
                <msb>3</msb>
                <lsb>0</lsb>
                <property name="hw_w" value="1"/>
                <property name="reset" value=""/>
                <property name="retention" value=""/>
                <property name="sw_r" value="1"/>
                <property name="width" value="0"/>
            </field>
        </reg>

Ответы [ 2 ]

0 голосов
/ 31 октября 2019
    for regfile in root.findall('regfile'):
        for reg in regfile.findall('reg'):
            reg_name = reg.find('name').text
            reg_name_quotes = '"'+reg_name+'"'
            reg_type = reg.get('type')
            reg_addr = reg.get('addr')
            reg_description = reg.find('description').text

Используя метод get, мы можем получить атрибуты.

0 голосов
/ 23 октября 2019

Вы можете использовать пакет xml.etree.ElementTree, чтобы проанализировать ваш xml-код в дереве и выполнить итерации по нему следующим образом:

# Official DOC: 
# https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree

import xml.etree.ElementTree as ET

x = '''<?xml version="1.0"?>
<regs>
    <reg regname="uid_v2" type="block_uid_v2_t" num="1" addr="0x4" incr="0x4"> </reg>
    <reg regname="uid_v3" type="block_uid_v3_t" num="3" addr="0x4" incr="0x4"> </reg>
</regs>'''

# tree = ET.parse("some_file.xml")
tree = ET.fromstring(x) # I use a string here in this example

for child in tree:
    print(child.tag, child.attrib)

child.attrib - это словарь: вы можете получить определенный атрибут введите просто child.attrib["type"]. Проверьте этот repl.it для живого примера .

РЕДАКТИРОВАТЬ - как запрошено в комментариях ниже:

# Get only the relevant nodes from the tree
for child in tree:
    if "type" in child.attrib:
        if child.attrib["type"] == "block_uid_v2_t":
            print(child.tag, child.attrib)

# List comprehension to store all relevant nodes in a list
regs = [child.attrib for child in tree if ("type" in child.attrib and child.attrib["type"]=="block_uid_v2_t")]

# Store only 'regname' of relevant nodes
reg_ids = [child.attrib["regname"] for child in tree if ("type" in child.attrib and child.attrib["type"]=="block_uid_v2_t")]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...