在Python 3中基于节点属性提取XML元素文本

时间:2016-06-20 13:53:31

标签: python xml xpath

我正在尝试从XML文件中提取各种信息。我可以部分地收集信息,但是我在走元素树时遇到困难,因为一些节点具有相同的名称,我不得不根据子节点中的属性名称进行提取。

以下是XML代码段:

<parent_element>
    <test_case name="00001d" run="1">
      <properties>
        <item name="ID">001029d</item>
        <item name="Test Description">Usefull Information</item>
      </properties>
      <runner>
        <iteration name="First Iter"/>
        <iteration name="1">
          <inputs>
            <input name="FirstInput">005546</input>
          </inputs>
          <step name="Setup"/>
          <step name="1">
            <action actual="0x00 01 1E" msg="INTERESTING.TAG" type="SET"/>
            <action actual="9" msg="TAG.LENGTH" type="SET"/>
            <action actual="10 10 01" msg="SOMETHING.RESULT" type="SET"/>
            <action actual="11 10 01" msg="OTHER.TYPE" type="SET"/>
          </step>
          <step name="ENDING"/>
        </iteration>
        <iteration name="TEST_END"/>
      </runner>
    </test_case>
</parent_element>

到目前为止,这是我的代码:

import lxml.etree as et 

doc = et.parse('C:/temp/report.xml')

testTags = doc.xpath('//test_case')
actionTags = doc.xpath('//test_case/runner/iteration/step')

for test in testTags:
    propertyTags = test.xpath('properties')
    for prop in propertyTags:
        print (prop[0].text)
        print(prop[1].text)
    for action in actionTags:   
        #print(action[0].text)
        #print(action[1].text)

我可以轻松抓取属性文本(&#39; 001029d&#39;以及&#39;有用信息&#39;)但我已经注释了我在上述代码中的位置。

我基本上需要参考&#39; msg =&#39;属性(例如&#34; INTERESTING.TAG&#34;)并提取&#39; actual =&#39;属性文本(例如0x00 01 1E)。或者,我缺少一种更有效的方法吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个:

import lxml.etree as et 

doc = et.parse('C:/temp/report.xml')

testTags = doc.xpath('//test_case')

for test in testTags:
  propertyTags = test.xpath('properties')
  actionTags = test.xpath('/runner/iteration/step/action')
  for prop in propertyTags:
      print (prop[0].text)
      print(prop[1].text)
  for action in actionTags:
     msg= action.attrib.get('msg')
     actual = action.attrib.get('actual')
     if msg=="INTERESTING.TAG" or msg=="SOMETHING.RESULT" :
        print(msg)
        print(actual)

警告我不知道python,语法的apolgies是不正确的。

您还可以包含更改xpath以过滤actionTags的大小,

  actionTags = test.xpath('/runner/iteration/step/action[@msg="INTERESTING.TAG" or @msg="SOMETHING.RESULT"]')
  for prop in propertyTags:
      print (prop[0].text)
      print(prop[1].text)
  for action in actionTags:
     msg= action.attrib.get('msg')
     actual = action.attrib.get('actual')
     print(msg)
     print(actual)
相关问题