获取XML节点的文本,包括子节点(或类似的东西)

时间:2013-08-26 11:54:07

标签: python xml

我必须从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-Node中可能有任何类型的“子节点”,我需要的只是BookTitle中的纯文本。

我试过了:

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

但是.text无法处理这个奇怪的xml节点并给我一个“NoneType”后面的

问候&amp;谢谢!

2 个答案:

答案 0 :(得分:2)

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

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

哪个应该给你一个基本的想法。

更新:修正了空白......

答案 1 :(得分:0)

您可以使用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_tags递归函数将浏览xml树并按顺序提取文本。

相关问题