繁体   English   中英

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

[英]Get Text for XML-Node including childnodes (or something like this)

我必须从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”

问候和谢谢!

这不是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

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

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

您可以使用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树并按顺序提取文本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM