关闭所有打开的 xml 标签 [英] Close all opened xml tags

查看:43
本文介绍了关闭所有打开的 xml 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,可在短时间内更改其内容.但我想在它准备好之前阅读它.问题是,它是一个 xml 文件(日志).因此,当您阅读它时,可能会发现并非所有标签都已关闭.

I have a file, which change it content in a short time. But I'd like to read it before it is ready. The problem is, that it is an xml-file (log). So when you read it, it could be, that not all tags are closed.

我想知道是否有可能正确关闭所有打开的标签,在浏览器中显示它没有问题(使用 xslt 样式表).这应该通过使用python包含的特性来实现.

I would like to know if there is a possibility to close all opened tags correctly, that there are no problems to show it in the browser (with xslt stylsheet). This should be made by using included features of python.

推荐答案

一些 XML 解析器允许对 XML 文档进行增量解析,即解析器可以开始处理文档而无需完全加载它.Python 标准库中 xml.etree.ElementTree 模块中的 XMLTreeBuilder 就是这样一种解析器:元素树

Some XML parsers allow incremental parsing of XML documents that is the parser can start working on the document without needing it to be fully loaded. The XMLTreeBuilder from the xml.etree.ElementTree module in the Python standard library is one such parser: Element Tree

正如您在下面的示例中所见,您可以在从输入源读取数据时将数据一点一点地提供给解析器.当发生各种 XML事件"(标记开始、标记数据读取、标记结束)时,将调用处理程序类中适当的钩子方法,允许您在加载 XML 文档时处理数据:

As you can see in the example below you can feed data to the parser bit by bit as you read it from your input source. The appropriate hook methods in your handler class will get called when various XML "events" happen (tag started, tag data read, tag ended) allowing you to process the data as the XML document is loaded:

from xml.etree.ElementTree import XMLTreeBuilder
class MyHandler(object):
    def start(self, tag, attrib):
        # Called for each opening tag.
        print tag + " started"
    def end(self, tag):
        # Called for each closing tag.
        print tag  + " ended"
    def data(self, data):
        # Called when data is read from a tag
        print data  + " data read"
    def close(self):    
        # Called when all data has been parsed.
        print "All data read"

handler = MyHandler()

parser = XMLTreeBuilder(target=handler)

parser.feed(<sometag>)
parser.feed(<sometag-child-tag>text)
parser.feed(</sometag-child-tag>)
parser.feed(</sometag>)
parser.close()

在此示例中,处理程序将接收五个事件并打印:

In this example the handler would receive five events and print:

sometag 开始

sometag-child 开始

sometag-child started

文本"数据读取

sometag-child 结束

sometag-child ended

sometag 结束

读取所有数据

这篇关于关闭所有打开的 xml 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆