2013-05-08 123 views
2
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,我想獲取鏈接和/鏈接之間的內容作爲字符串。 請讓我知道如何。如何獲取python中兩個xml標籤之間的內容?

回答

2

如果你想堅持xml.dom的.minidom只需調用.firstChild.nodeValue。例如,存儲在變量「鏈表」中的鏈接,所以打印出來簡單地遍歷它們並呼籲.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] 
+0

那麼,我該如何獲得某個元素?不打印所有 – user2351602 2013-05-08 13:22:42

+0

您需要知道它的位置或所需元素的文字。我會附上一些例子。 – b10hazard 2013-05-08 13:27:45

1

這比看起來更復雜。從文檔中的例子,在你的問題把這段代碼:

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 

我建議嘗試the elementtree module其中代碼如下:

print linklist[0].text 
+0

+1 ElementTree的(或者,如果需要更多的LXML) – Mark 2013-05-08 13:05:00

+0

回溯(最近最後一次通話): 文件 「C:/Users/lee/Desktop/www.py」第28行,在 text = getText(linklist [0] .childNodes) 文件「C:/Users/lee/Desktop/www.py」,第24行,在getText中 if node.nodetype == node.TEXT_NODE: AttributeError:'文本'對象沒有屬性'nodetype'我收到一條錯誤消息。 – user2351602 2013-05-08 13:08:56

相關問題