如何从python中的xml文件读取字典中的xml内容?

时间:2019-04-23 19:24:21

标签: python xml python-3.x

我如何读取xml文件并加载内容,类似于json示例。 共享的json代码仅供参考,正在运行,我想以类似方式加载xml内容。曾尝试在xml中进行最小限度解析,但是当我尝试从读取的内容中获取方法时,会抛出错误AttributeError: keys_exists() expects dict as first argument.

with open(xml_file) as f:
        content = f.read()
        self.spec = xml.loads(content)

json file can load the content as : 
  with open(json_file) as f:
    content = f.read()
    self.spec = json.loads(content)

尝试了xml的minidom解析:

    with open(xml_file) as f:
       self.spec = minidom.parse(xml_file)

尝试获取方法,但在执行时显示错误AttributeError: keys_exists() expects dict as first argument.

 def get_methods(self):
      ''' Get all the methods 
      Return:
      All the methods (array)          
      '''
      list_methods = []
      if keys_exists(self.spec,self.name,'methods'):
             for action in self.spec[self.name]['methods'].keys():
                   for method in self.spec[self.name]['methods'] [action].keys():
                        if method == 'method':

                                list_methods.append(self.spec[self.name]['method'] [action][method])
      return list_methods

xml文件格式:

<class>
<grpname>test123</grpname>
<name>test123_binding</name>
<descr>test</descr>
<properties>
    <property>
        <name>test</name>
        <type>test_binding[]</type>
        <access>readonly</access>
    </property>
    <property>
        <name>test_action_binding</name>
        <type>test_action_binding[]</type>
        <access>readonly</access>
    </property>
</properties>
<methods>
    <method>
        <name>get</name>
        <in-parameters>
            <parameter>
                <name>session</name>
                <type>service</type>
                <mandatory>true</mandatory>
            </parameter>
        </in-parameters>
        <out-parameter>
            <parameter>
                <type>test_binding</type>
            </parameter>
        </out-parameter>
    </method>
</methods>

0 个答案:

没有答案