python - 如何使用 xml.dom 中的 minidom 获取字符串形式的内部内容?

标签 python xml python-3.x minidom

我的 xml 文件中有一些文本标签(使用 popplers-utils 中的 pdftohtml 将 pdf 转换为 xml),如下所示:

<text top="525" left="170" width="603" height="16" font="1">..part of old large book</text>
<text top="546" left="128" width="645" height="16" font="1">with many many pages and some <i>italics text among 'plain' text</i> and more and more text</text>
<text top="566" left="128" width="642" height="16" font="1">etc...</text>

我可以使用以下示例代码获取包含文本标记的文本:

import string
from xml.dom import minidom
xmldoc = minidom.parse('../test/text.xml')
itemlist = xmldoc.getElementsByTagName('text')

some_tag = itemlist[node_index]
output_text = some_tag.firstChild.nodeValue
# if there is all text inside <i> I can get it by
output_text = some_tag.firstChild.firstChild.nodeValue

# but no if <i></i> wrap only one word of the string

但如果“nodeValue”包含另一个标签,我无法获取它 (<i> or <b>...)里面也无法获取对象

将所有文本获取为纯字符串(如 javascript insideHTML 方法)或递归到子标记(即使它们包含一些单词而不是整个 nodeValue)的最佳方法是什么?

谢谢

最佳答案

**Question: How to get inner content as string using minidom

这是一个递归解决方案,例如:

def getText(nodelist):
    # Iterate all Nodes aggregate TEXT_NODE
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
        else:
            # Recursive
            rc.append(getText(node.childNodes))
    return ''.join(rc)


xmldoc = minidom.parse('../test/text.xml')
nodelist = xmldoc.getElementsByTagName('text')

# Iterate <text ..>...</text> Node List
for node in nodelist:
    print(getText(node.childNodes))

Output:

..part of old large book
with many many pages and some italics text among 'plain' text and more and more text
etc...

使用 Python 测试:3.4.2

关于python - 如何使用 xml.dom 中的 minidom 获取字符串形式的内部内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603446/

相关文章:

python - 用python编写命令并在powershell中执行

xml - 编写 XSLT 将带有属性名称的 XML 转换为标签

python - 在 Sphinx 中禁用语法突出显示(Alabaster 主题)

python - 使用 Python unittest 测试可以返回不确定结果的函数

java - 在 Activity 时实现后退按钮(物理)Android

列表中的 Python 唯一值

pandas - 如何找出多索引 pandas 数据帧的索引中是否缺少给定的数字/文本?

python-3.x - 币安公告页面上的 Beautiful Soup Web Scraper 滞后 5 分钟

python - 使用 PyCharm 编写脚本参数 - Learn Python the Hard way

java - Android Studio 中的 fragment 在虚拟机中彼此堆叠