XML子树解析

3

我需要使用lxml或者xml.etree.ElementTree模块来解析一个XML文件。

<?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={
      'modname' => { 
        'Min' : 0.00073,
        'Max': 0.32420,
       }
 }
3个回答

2
我使用了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

输出:

dict={
      'modname' : { 
        'Min' : 0.00073,
        'Max': 0.32420,
       }
}

2

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))

只需一行代码,您就可以开始使用。

希望这对您有用。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接