使用python scrip从xml中提取属性和某些标记值

2024-05-02 16:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析一个XML内容并返回一个字典,其中只包含name属性及其值作为dictionary。例如:

  <ecmaarray>
   <number name="xyz1">123.456</number>  
   <ecmaarray name="xyz2">  
       <string name="str1">aaa</string>  
       <number name="num1">55</number>  
   </ecmaarray>  
   <strictarray name="xyz3">  
       <string>aaa</string>  
       <number>55</number>  
   </strictarray>  
</ecmaarray>  

输出必须在类似这样的字典中。。你知道吗

Dict:{ 'xyz1': 123.456, 
       'xyz2': {'str1':'aaa', 'num1': '55'},
       'xyz3': ['aaa','55']
     }

有人能提出一个递归的解决方案吗?你知道吗


Tags: namenumber内容string字典属性xmlaaa
1条回答
网友
1楼 · 发布于 2024-05-02 16:01:11

假设情况是这样的:

<strictarray name="xyz4">
    <string>aaa</string>
    <number name="num1">55</number>
</strictarray>

不可能,下面是使用lxml的示例代码:

from lxml import etree


tree = etree.parse('test.xml')

result = {}
for element in tree.xpath('/ecmaarray/*'):
    name = element.attrib["name"]
    text = element.text
    childs = element.getchildren()

    if not childs:
        result[name] = text
    else:
        child_dict = {}
        child_list = []
        for child in childs:
            child_name = child.attrib.get('name')
            child_text = child.text
            if child_name:
                child_dict[child_name] = child_text
            else:
                child_list.append(child_text)

        if child_dict:
            result[name] = child_dict
        else:
            result[name] = child_list


print result

印刷品:

{'xyz3': ['aaa', '55'], 
 'xyz2': {'str1': 'aaa', 'num1': '55'}, 
 'xyz1': '123.456'}

您可能需要改进代码-这只是一个关于去哪里的提示。你知道吗

希望有帮助。你知道吗

相关问题 更多 >