Python - 没有明确的XML - 标签和值混合在一起

时间:2015-08-17 23:50:43

标签: python xml parsing

在下一节中,解析时我正在打印标题,价格而不是书籍ID。提前谢谢大家。

以下尝试阅读书籍ID,标题,价格并打印出来 booksExample.xml文件的示例结构

<book id="bk101">
  <author>F-NAME, L-NAME</author>
  <title>BOOK'S TITLE</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <description>ANALYTICAL INFORMATION ABOUT IT.</description>
</book>

代码:

from xml.etree.ElementTree import parse
doc = parse('booksExample.xml')

for book in doc.findall('book'):
   id = book.findtext('id')
   title = book.findtext('title')
   price = book.findtext('price')
   print id, title, price

1 个答案:

答案 0 :(得分:1)

book.get('id')是book元素的属性,因此您必须使用book.findtext('id'),而不是from xml.etree.ElementTree import parse doc = parse('booksExample.xml') for book in doc.findall('book'): id = book.get('id') title = book.findtext('title') price = book.findtext('price') print id, title, price

<强> parse.py:

booksExample.xml

仅供参考,使用以下(parsexml)macbook:parsexml joeyoung$ python parse.py bk101 XML Developer's Guide 44.95 bk102 Midnight Rain 5.95 bk103 Maeve Ascendant 5.95 bk104 Oberon's Legacy 5.95 bk105 The Sundered Grail 5.95 bk106 Lover Birds 4.95 bk107 Splish Splash 4.95 bk108 Creepy Crawlies 4.95 bk109 Paradox Lost 6.95 bk110 Microsoft .NET: The Programming Bible 36.95 bk111 MSXML3: A Comprehensive Guide 36.95 bk112 Visual Studio 7: A Comprehensive Guide 49.95 https://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx

<强>输出:

=IF(NOT(ISBLANK(H2)),vlookup(H2,Tags!A2:B64,2,FALSE),"")