繁体   English   中英

XML从python中的文件中读取最后一个条目

[英]XML reading the last entry from the file in python

我想读取xml文件的最后一个条目并获取其值。 这是我的xml文件

<TestSuite>
  <TestCase>
    <name>tcname1</name>
    <total>1</total>
    <totalpass>0</totalpass>
    <totalfail>0</totalfail>
    <totalerror>1</totalerror>
  </TestCase>
  <TestCase>
    <name>tcname2</name>
    <total>1</total>
    <totalpass>0</totalpass>
    <totalfail>0</totalfail>
    <totalerror>1</totalerror>
  </TestCase>
</TestSuite>

我想获得<total><totalpass> <totalfail><totalerror>在文件的最后一个标记值。 我已经尝试过此代码来做到这一点。

import xmltodict
with open(filename) as fd:
    doc = xmltodict.parse(fd.read())
    length=len(doc['TestSuite']['TestCase'])
    tp=doc['TestSuite']['TestCase'][length-1]['totalpass']
    tf=doc['TestSuite']['TestCase'][length-1]['totalfail']
    te=doc['TestSuite']['TestCase'][length-1]['totalerror']
    total=doc['TestSuite']['TestCase'][length-1]['total']

该方法适用于xml文件中具有2个或更多测试用例标签的xml,但是对于仅具有一个测试用例标签的文件,由于此错误而失败。

Traceback (most recent call last):
  File "HTMLReportGenerationFromXML.py", line 52, in <module>
    tp=doc['TestSuite']['TestCase'][length-1]['totalpass']
KeyError: 4 .

因为它代替了count,而是采用子标签(等值作为长度)。 请帮助我解决此问题。

我为什么首先不做他的事! 使用xpath。

第一个示例涉及仅使用一个TestCase元素处理xml文件,第二个示例涉及其中两个元素。 关键是使用xpath last选择器。

>>> from lxml import etree
>>> tree = etree.parse('temp.xml')
>>> last_TestCase = tree.xpath('.//TestCase[last()]')[0]
>>> for child in last_TestCase.iterchildren():
...     child.tag, child.text
... 
('name', 'tcname2')
('total', '1')
('totalpass', '0')
('totalfail', '0')
('totalerror', '1')
>>> 
>>> tree = etree.parse('temp_2.xml')
>>> last_TestCase = tree.xpath('.//TestCase[last()]')[0]
>>> for child in last_TestCase.iterchildren():
...     child.tag, child.text
... 
('name', 'tcname1')
('reason', 'reason')
('total', '2')
('totalpass', '0')
('totalfail', '0')
('totalerror', '2')

由于只需要最后一个,因此可以使用负索引来检索它:

import xml.etree.ElementTree as et

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

# collect all the test cases
test_cases = [test_case for test_case in tree.findall('TestCase')]

# Pull data from the last one
last = test_cases[-1]
total = last.find('total').text
totalpass = last.find('totalpass').text
totalfail = last.find('totalfail').text
totalerror = last.find('totalerror').text

print total,totalpass,totalfail,totalerror

您出错的原因是,使用xmltidict doc['TestSuite']['TestCase']是仅用于长XML的列表

>>> type(doc2['TestSuite']['TestCase']) # here doc2 is more than one-entry long XML file 
>>> list

但这只是一个单入口长文件的字典:

>>> type(doc['TestSuite']['TestCase']) # doc is one-entry long 
>>> collections.OrderedDict

这就是原因。 您可以尝试通过以下方式解决问题:

 import xmltodict
 with open(filename) as fd:
    doc = xmltodict.parse(fd.read())

    if type(doc['TestSuite']['TestCase']) == list:    
        tp=doc['TestSuite']['TestCase'][length-1]['totalpass']

        tf=doc['TestSuite']['TestCase'][length-1]['totalfail']

        te=doc['TestSuite']['TestCase'][length-1]['totalerror']

        total=doc['TestSuite']['TestCase'][length-1]['total']

   else: # you have just a dict here
        tp=doc['TestSuite']['TestCase']['totalpass']

        tf=doc['TestSuite']['TestCase']['totalfail']

        te=doc['TestSuite']['TestCase']['totalerror']

        total=doc['TestSuite']['TestCase']['total']

否则,您可以使用另一个库进行XML解析。

...让我知道是否有帮助!

我已经尝试过这个对我有用

import xml.etree.ElementTree as ET
import sys
tree = ET.parse('temp.xml')
root = tree.getroot()
print root
total=[]
totalpass=[]
totalfail=[]
totalerror=[]
for test in root.findall('TestCase'):
    total.append(test.find('total').text)
    totalpass.append(test.find('totalpass').text)
    totalfail.append(test.find('totalfail').text)
    totalerror.append(test.find('totalerror').text)
length=len(total)
print total[length-1],totalpass[length-1],totalfail[length-1],totalerror[length-1]

这个对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM