2017-02-16 58 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