获取XMLNode的文本,包括childnodes(或类似的内容)

2024-06-28 04:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须从xml节点及其子节点中获取纯文本,或者这些奇怪的内部标记是什么:

示例节点:

<BookTitle>
<Emphasis Type="Italic">Z</Emphasis>
 = 63 - 100
</BookTitle>

或:

<BookTitle>
Mtn
<Emphasis Type="Italic">Z</Emphasis>
 = 74 - 210
</BookTitle>

我必须得到:

Z = 63 - 100
Mtn Z = 74 - 210

记住,这只是一个例子!BookTitle节点中可以有任何类型的“子节点”,我所需要的只是BookTitle中的纯文本。你知道吗

我试过:

tagtext = root.find('.//BookTitle').text
print tagtext

但是.text无法处理这种奇怪的xml节点,并返回“NoneType”

问候与感谢!你知道吗


Tags: text标记文本示例类型节点typeroot
2条回答

您可以使用minidom解析器。举个例子:

from xml.dom import minidom

def strip_tags(node):
    text = ""
    for child in node.childNodes:
        if child.nodeType == doc.TEXT_NODE:
            text += child.toxml()
        else:
            text += strip_tags(child)
    return text

doc = minidom.parse("<your-xml-file>")

text = strip_tags(doc)

strip\u tags递归函数将浏览xml树并按顺序提取文本。你知道吗

那不是BookTitle节点的text,而是Emphasis节点的tail。所以你应该这样做:

def parse(el):
    text = el.text.strip() + ' ' if el.text.strip() else ''
    for child in el.getchildren():
        text += '{0} {1}\n'.format(child.text.strip(), child.tail.strip())
    return text

这给了你:

>>> root = et.fromstring('''
    <BookTitle>
    <Emphasis Type="Italic">Z</Emphasis>
     = 63 - 100
    </BookTitle>''')
>>> print parse(root)
Z = 63 - 100

以及:

>>> root = et.fromstring('''
<BookTitle>
Mtn
<Emphasis Type="Italic">Z</Emphasis>
 = 74 - 210
</BookTitle>''')
>>> print parse(root)
Mtn Z = 74 - 210

这应该给你一个基本的想法怎么做。你知道吗

更新:修复了空格。。。你知道吗

相关问题 更多 >