XML子树解析

2024-09-29 22:29:36 发布

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

我必须使用lxml或者甚至xml.etree.ElementTree模块

<?xml version="1.0"?>
<corners>
  <version>1.05</version>
  <process>
    <name>ss649</name>
    <statistics>
      <statistic name="Min" forparameter="modname" isextreme="no" style="tbld">
        <value>0.00073</value>
        <real_value>7.300e-10</real_value>
      </statistic>
      <statistic name="Max" forparameter="modname" isextreme="no" style="tbld">
        <value>0.32420</value>
        <real_value>3.242e-07</real_value>
     </statistic>
     <variant>
          <name>Unit</name>
          <value>
            <value>Size</value>
            <statistics>
              <statistic name="Min" forparameter="modname1" isextreme="no" style="tbld">
                <value>0.02090</value>
                <real_value>2.090e-08</real_value>
              </statistic>
              <statistic name="Max" forparameter="modname2" isextreme="no" style="tbld">
                <value>0.02090</value>
                <real_value>2.090e-08</real_value>
              </statistic>
         </variant>

我必须把所有的值都取出来,然后做一个Dict,这个值是哪个,但是我不能访问子树,我该怎么做呢?在

尝试创建一个像这样的dict

^{pr2}$

Tags: nonamevaluestyleversionxmlminstatistic
3条回答

您可能希望看看这个相当不错的ActiveState片段:

http://code.activestate.com/recipes/410469-xml-as-dictionary/

我是通过下面的SO帖子看到的,这个帖子可能也有用:

How to convert an xml string to a dictionary in Python?

xmltodict也是一个不错的选择:

https://github.com/martinblech/xmltodict

xmltodict绝对是您应该考虑使用的内容:

from pprint import pprint
import xmltodict

data = """<?xml version="1.0"?>
<corners>
  <version>1.05</version>
  <process>
    <name>ss649</name>
    <statistics>
      <statistic name="Min" forparameter="modname" isextreme="no" style="tbld">
        <value>0.00073</value>
        <real_value>7.300e-10</real_value>
      </statistic>
      <statistic name="Max" forparameter="modname" isextreme="no" style="tbld">
        <value>0.32420</value>
        <real_value>3.242e-07</real_value>
     </statistic>
    </statistics>
  </process>
</corners>"""

pprint(xmltodict.parse(data))

一行代码,你就可以走了。在

希望对你有用。在

我使用了xml.etree.ElementTree模块

dict = {}
tree = ET.parse('file.xml')
root=tree.getroot()
for attribute in root:
        for stats in attribute.iter('statistics'):  #Accessing to child tree of the process 'attribute'
            for sub_att in stats.iter('statistic'): #Iterating trough the attribute items
                    name      =  sub_att.get('name')
                    parameter =  sub_att.get('forparameter')
                    for param_value in sub_att.iter('value'):
                         value = param_value.text   #Collecting the value of the sub_attribute
                         break                      #Speed up the script, skips the <real_value>
            if not dict.has_key(parameter):
                    dict[parameter] = {}
            dict[parameter][name] = value

输出:

^{pr2}$

相关问题 更多 >

    热门问题