python - 使用 QXmlStreamReader 的 XML 解析不返回所有元素

标签 python xml qt pyqt qxmlstreamreader

我正在尝试使用 QXmlStreamReader 解析 XML 文件。使用以下代码,我只能从示例 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>

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

最佳答案

随着数据 QXmlStreamReader 逐渐读取数据,并非所有数据都可能在 QIODevice 的缓冲区中可用。从慢速设备读取数据时尤其如此,例如网络套接字,但也可能在从本地文件读取时发生。

阅读更多关于如何处理在 "Incremental parsing" section of the QXmlStreamReader documentation 中以 block 形式到达的数据.

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

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

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

关于python - 使用 QXmlStreamReader 的 XML 解析不返回所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480871/

相关文章:

Python 电子邮件标题奇怪的行为

xml - 如何使用 xqilla 命令行工具为 xpath 定义命名空间?

ruby - 如何在 ruby​​ 中使用 Mechanize 和 XMLSimple 解析 XML?

c++ - 列出tableView中两个表的数据

c++ - QSerialPort连续读取累计延时

c++ - 从C++中的共享库调用指向列表的静态指针

python - 将 tastypie 导入到项目中

python - django `makemigrations` 底层是如何工作的?

python - 确定二维数组中最长连续值范围的最快方法

xml - 正确的结构布局以在 go 中解析 xml