3

我正在尝试XML使用QXmlStreamReader. 使用以下代码,我只能从示例 xml 文件中获取第一个测试用例。

from PyQt4.QtCore import QXmlStreamReader, QFile, QIODevice

class TestcaseReader(object):
    def __init__(self, filename):
        file = QFile(filename)
        file.open(QIODevice.ReadOnly)
        self.xml = QXmlStreamReader(file)

        while not self.xml.atEnd():
            self.xml.readNext()
            if self.xml.isStartElement():
                if self.xml.name() == "Testcase":
                    self.parse_testcase()

    def parse_testcase(self):
        print("Parse Testcase")
        while self.xml.readNextStartElement():
            if self.xml.name() == "Type":
                measurement = self.xml.readElementText()
                print("Type: " + measurement)
            elif self.xml.name() == "Attributes":
                name = self.xml.attributes().value("name")
                strname = self.xml.attributes().value("strname")
                elementtype = self.xml.attributes().value("type")
                value = self.xml.attributes().value("value")
                print("Attributes: ", name, strname, elementtype, value)

if __name__ == "__main__":
    print("XML Reader")
    xml = TestcaseReader("test.xml")

这是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<Testcases>
    <Testcase>
        <Type>Testtype1</Type>
        <Attributes name="testattr1" strname="Testattribute 1" type="float" value="1.0">
        <Attributes name="testattr2" strname="Testattribute 2" type="str" value="test">
    </Testcase> 
    <Testcase>
        <Type>Testtype2</Type>
        <Attributes name="testattr1" strname="Testattribute 1" type="float" value="2.0">
        <Attributes name="testattr2" strname="Testattribute 2" type="str" value="test">
    </Testcase>
</Testcases>

Testcase从QXmlStreamReader解析第一个Testcases返回后,它位于末尾,因此停止进一步解析。如何从 xml 文件中读取所有测试用例?

4

1 回答 1

2

由于数据 QXmlStreamReader 以增量方式读取数据,因此 QIODevice 的缓冲区中可能并非所有数据都可用。从慢速设备(例如网络套接字)读取数据时尤其如此,但从本地文件读取数据时也会发生这种情况。

阅读QXmlStreamReader 文档的“增量解析”部分中有关如何处理以块形式到达的数据的更多信息。

此外,您的 XML 无效,它应该读取<Attributes ... />而不是<Attributes ...>. 例如,对于第一个:

<Attributes name="testattr1" strname="Testattribute 1" type="float" value="1.0"/>

QXmlStreamReader 的 error()、errorString()、errorLine() 和 errorColumn() 应该为您提供调试此类问题所需的所有信息。(检查错误并正确报告它们是一种很好的做法)。

于 2012-09-18T17:15:45.677 回答