简体   繁体   English

Python-没有明确的XML-标记和值混合

[英]Python - no clear XML - tags and values mixed

In the following section, while parsing I am getting correct printing for title, price but not for book id. 在以下部分中,在解析时,我将获得正确的标题,价格打印信息,而不是图书ID的打印信息。 Thank you all in advance. 谢谢大家。

The following tries to read book id, title, price an print them example structure of the booksExample.xml file 以下尝试读取书籍ID,书名,价格并打印它们,这些文件都是examplesExample.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>

Code: 码:

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

id is an attribute of the book element so you have to use book.get('id') , not book.findtext('id') id是book元素的属性,因此您必须使用book.get('id') ,而不是book.findtext('id')

parse.py: parse.py:

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

Just for reference, using the following as booksExample.xml : https://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx 仅供参考,将以下内容用作booksExample.xmlhttps : booksExample.xml = booksExample.xml

output: 输出:

(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM