python - 解析 XML Python

标签 python xml parsing xml-parsing newline

我正在使用 xml.etree.ElementTree 来解析 XML 文件。我有个问题。我不知道如何获取标签之间的纯文本行。

<Sync time="4.496"/>
<Background time="4.496" type="music" level="high"/>

<Event desc="pause" type="noise" extent="instantaneous"/>
Plain text
<Sync time="7.186"/>

<Event desc="b" type="noise" extent="instantaneous"/>
Plain text
<Sync time="10.949"/>
Plain text

我已经有了这个代码:

import xml.etree.ElementTree as etree
import os

data_file = "./file.xml"

xmlD = etree.parse(data_file)
root = xmlD.getroot()
sections = root.getchildren()[2].getchildren()
for section in sections:
    turns = section.getchildren()
    for turn in turns:
        speaker = turn.get('speaker')
    mode = turn.get('mode')
    childs = turn.getchildren()

        for child in childs:
            time = child.get('time')
            opt = child.get('desc')
            if opt == 'es':
                 opt = "ESP:"
            elif opt == "la":
                 opt = "LATIN:"
            elif opt == "*":
                 opt = "-ININT-"
            elif opt == "fs":
                 opt = "-FS-"
            elif opt == "throat":
                 opt = "-THROAT-"
            elif opt == "laugh":
                 opt = "-LAUGH-"
            else:
                 opt = ""

            print speaker, mode, time, opt+child.tail.encode('latin-1')

我可以通过 XML 访问 Sync|Background|Event 标记之前的内容,但无法提取这些标记之后的文本。我放置了 XML 文件的一部分,而不是整个文件。我只对最后一段代码有问题

非常感谢@alecxe。现在我可以获得我需要的信息。但现在我有一个新的小问题。我获得了键入 tail 命令的行,但之前生成了换行符 \n 或类似的内容,因此,我需要类似的内容: spk1计划的LAN:来自尾部的纯文本>

但我明白了:

spk1 规划的 LAN: 尾部纯文本

我在处理XML后尝试了很多东西,re.match()模块,sed命令,但似乎没有\n 新行字符,但我无法“放置”纯文本!预先感谢您

有人吗?谢谢!

最佳答案

这称为 tail of an element :

The tail attribute can be used to hold additional data associated with the element. This attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found after the element’s end tag and before the next tag.

找到Event标签并获取尾部,例如:

section.find("Event").tail

关于python - 解析 XML Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30166240/

相关文章:

Java XML 读取器错误

java - 使用 JAXB 从 XSD 生成元素 java 类

python - 使用 Python 保存 Outlook 附件

python - 无法获取 URL https ://pypi. python.org/simple/xlrd/

python - 在 Python 中动态创建函数和线程

python - 获取时间点,并针对日期时间对象制作标签以关联点周围的事物

java - 无法从 android.app.Application 转换为自定义类型

python - django如何获取 View 中的小数总和?

json - 将谷歌地图自动完成 api 与 select2 一起使用

json - 请帮我弄清楚如何解析这个json文件