2017-02-16 60 views
0

從XML值我想使用Python如何閱讀在Python

<book id="bk101"> 
    <author Value="J.K.Rowling" /> 
    <title Value="Harry Potter"/> 
</book> 

代碼從下面的XML閱讀作者和標題的值:

member.find('author').text 
# returns None. 
+0

你能包括你的python代碼嗎? – Danoram

+0

代碼請!你想要一個屬性值,而不是文本。也許'member.find('author')。attrib ['Value']'會給你你想要的。 – tdelaney

+0

代碼應包含用於解析XML的模塊。他們有不同的方法來處理屬性。 – tdelaney

回答

1

製作的XML一些假設庫你使用,下面是一個使用xml.dom.minidom一個例子:

from xml.dom import minidom 

xml_string = """<book id="bk101"> 
    <author Value="J.K.Rowling" /> 
    <title Value="Harry Potter"/> 
</book>""" 

# Parse 
root = minidom.parseString(xml_string) 
author_list = root.getElementsByTagName("author") 

for author in author_list: 
    value = author.getAttribute("Value") 
    print("Found an author with value of {0}".format(value)) 

輸出:

Found an author with value of J.K.Rowling