如何在python中获取两个xml标记之间的内容? import xml.dom.minidom 水=“” 水 http://www.water.com 火 http://www.fire.com """ dom=xml.dom.minidom.parseString(水) linklist=dom.getElementsByTagName('link') 打印(len(链接列表))

如何在python中获取两个xml标记之间的内容? import xml.dom.minidom 水=“” 水 http://www.water.com 火 http://www.fire.com """ dom=xml.dom.minidom.parseString(水) linklist=dom.getElementsByTagName('link') 打印(len(链接列表)),python,xml,parsing,Python,Xml,Parsing,使用minidom,我希望以字符串的形式获取link和/link之间的内容。 请告诉我怎么做。这比看起来要复杂。根据文档中的示例,将其附加到问题中的代码中: import xml.dom.minidom water = """ <channel> <item> <title>water</title> <link>http://www.water.com</link> </item> <item>

使用minidom,我希望以字符串的形式获取link和/link之间的内容。
请告诉我怎么做。

这比看起来要复杂。根据文档中的示例,将其附加到问题中的代码中:

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))
我建议尝试代码所在的位置:

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

text = getText(linklist[0].childNodes)
print text

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

print linklist[0].text
印刷品

for link in linklist:
    print link.firstChild.nodeValue
这里有更详细的答案。。。。


回答您的另一个问题:
如果您想获得一个特定的元素,您需要知道它在文档中的位置或搜索它

例如,如果您知道您想要的链接是xml文档中的第二个链接,那么您可以

http://www.water.com
http://www.fire.com
但是,如果您想要链接,但不知道它在文档中的位置,则必须搜索它。这里有一个例子

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

回溯(最近一次调用):文件“C:/Users/lee/Desktop/www.py”,第28行,文本=getText(链接列表[0].childNodes)文件“C:/Users/lee/Desktop/www.py”,第24行,在getText中,如果node.nodetype==node.TEXT\u node:AttributeError:'TEXT'对象没有属性'nodetype',我收到一条错误消息。那么,如何获取某个元素?如果不打印所有内容,则需要知道它的位置或所需元素的文本。我将附加一些示例。
# 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]