python - 如何在python中获取两个xml标签之间的内容?

标签 python xml parsing

import xml.dom.minidom

water = """
<channel>
<item>
<title>water</title>
<link>http://www.water.com</link>
</item>
<item>
<title>fire</title>
<link>http://www.fire.com</link>
</item>
</channel>"""

dom=xml.dom.minidom.parseString(water)
linklist = dom.getElementsByTagName('link')
print (len(linklist))

使用 minidom,我想获取 link 和/link 之间的内容作为字符串。 请让我知道如何做。

最佳答案

如果您想坚持使用 xml.dom.minidom,只需调用 .firstChild.nodeValue。例如,您将链接存储在变量“linklist”中,因此要打印它们,只需迭代它们并调用 .firstChild.nodeValue,如下所示...

for link in linklist:
    print link.firstChild.nodeValue

打印...

http://www.water.com
http://www.fire.com

更详细的答案在这里...... Get Element value with minidom with Python


回答您的其他问题:
如果您想获取特定元素,您需要知道它在文档中的位置或搜索它。

例如,如果您知道所需的链接是 xml 文档中的第二个链接,您会执行...

# the variable fire_link is a DOM Element of the second link in the xml file
fire_link = linklist[1]

但是,如果您想要该链接但不知道它在文档中的位置,则必须进行搜索。这是一个例子...

# fire_link is a list where each element is a DOM Element containing the http://www.fire.com link
fire_links = [l for l in linklist if l.firstChild.nodeValue == 'http://www.fire.com']

# take the first element
fire_link = fire_links[0]

关于python - 如何在python中获取两个xml标签之间的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16441354/

相关文章:

javascript - 使用 babel 解析器时,Eslint 禁用严格模式

python - joblib 中的 batch_size 和 pre_dispatch 到底是什么意思

python - Pytorch:我们可以直接在 forward() 函数中使用 nn.Module 层吗?

android - 使 Android 布局可滚动

java - 解决使用 SAX 解析器解析 xml 的安全问题

java - Groovy 类的 XML 序列化

c++ - 使用 boost 正则表达式解析文本文件

java - 自动向数组添加元素

python - 如何在 JSON 文件中附加字典,同时保持正确的 JSON 格式

python - 脚本打印乱序