python - 元素树、解析XML没有出现在QLineEdit中

标签 python xpath xml-namespaces elementtree

我在QGIS中制作插件来打开并解析本地磁盘或可移动磁盘中的xml,这是我用来打开xml文件的代码:

from PyQt4 import QtCore, QtGui
from ui_testparse import Ui_testparse
import xml.etree.ElementTree as ETree
# create the dialog for zoom to point


class testparseDialog(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_testparse()
        self.ui.setupUi(self)

        opendata = self.ui.btnCari
        QtCore.QObject.connect(opendata, QtCore.SIGNAL('clicked()'),self.openxml)

    def openxml(self, event=None):

        #open dialog
        openfile = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')

        self.ui.lineLokasi.setText(openfile)

        #call XML data
        self.isiData(openfile)

    def isiData(self, nmsatu):
        #open teks with read mode
        openteks = open(nmsatu, 'r').read()

        self.ui.textXml.setText(openteks)

然后我尝试使用元素树来解析 xml,我用这段代码从上面的代码中解析 xml:

#Parse XML from Above
        self.parsenow(openteks)

    def parsenow(self, parse):
        element = ETree.fromstring(parse)
        xml_obj = ETree.ElementTree(element)
        for title_obj in xml_obj.findall('./{gmd#}dateStamp/{gco#}Date'):
            print element
            self.ui.lineSkala.setText(element)

我想要解析的 xml 格式如下:

<gmd:datestamp>
<gco:Date> XML Date </gco:Date>

我尝试在QT中的LineSkala(lineEdit)中显示XML日期,但是当我运行它时,它可以打开并读取xml,但无法在lineSkala中显示XML日期 ,它只是空白,没有给我任何错误消息

我想念什么? 感谢您提前的帮助

最佳答案

XPath syntax supported by etree是相当有限的。此外,您必须在使用 find/findall 时提供前缀字典。 (尽管这在 python2 中没有正确记录),或者使用完整的命名空间 uri。

所以尝试这样的事情:

ns = {
    'gmd': 'http://www.isotc211.org/2005/gmd',
    'gco': 'http://www.isotc211.org/2005/gco',
    }

tree.findall('.//gmd:dateStamp/gco:Date', ns)

或者:

tree.findall('.//{http://www.isotc211.org/2005/gmd}dateStamp/'
             '{http://www.isotc211.org/2005/gco}Date')

附注:

如果您需要使用更复杂的 XPath 语法,请尝试 lxml ,它具有与 ElementTree 非常相似的 API,但具有更多功能。

关于python - 元素树、解析XML没有出现在QLineEdit中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22811387/

相关文章:

python - 导入错误: cannot import name 'Affiliate' from partially initialized module 'affiliate.models' (most likely due to a circular import)

python - 子图的不同行高

c# - 查找任何具有自定义前缀 HtmlAgilityPack 的互文

python lxml 在 windows 和 linux 上的不同结果

c# - namespace 不是其父 namespace 的 XML 属性被反序列化为 null

python - python webpy框架中缓存控制的正确方法是什么

python - 如何编写自引用 Django 模型?

xpath - 如何在 wso2 ESB 中对多个参数使用过滤器

c# - 使用命名空间将类序列化为 XML

c# - 无法使用 C# 从 XElement 中删除空的 xmlns 属性