【发布时间】:2017-03-10 13:22:38
【问题描述】:
我现在正在学习 Python 2.6.4 版本 我要做的第一件事是尝试仅解析属性(orderno)的值并将其打印出来。 其次,我试图解析 XML 并从属性“orderno”中找到像 10238 这样的属性的值,但是将整个项目打印为像“10238,1,Hasselblad 501 CM body,2355”这样的 csv 行 有什么具体的方法吗?
from xml.etree import ElementTree
tree = ElementTree.parse('sample.xml')
root = tree.getroot()
for item in root:
first = item.find('orderno').text
print first
数据:
<item>
<orderno>10238</orderno>
<count>1</count>
<name>Hasselblad 501 CM body</name>
<price>2355</price>
</item>
<item>
<orderno>20032</orderno>
<count>1</count>
<name>Carl Zeiss Planar Lens CB 2.8/80 mm</name>
<price>1233</price>
</item>
<item>
<orderno>30212</orderno>
<count>1</count>
<name>Roll Film 120 Magazine A12</name>
<price>917</price>
</item>
【问题讨论】:
-
如果数据有
<items>标签会更容易 -
这只是一个例子。我编辑了 sample.xml。
-
嗯,如果这是python,那么它非常需要代码缩进,目前的只是让我感到困惑
-
您的 xml 未更改不会影响我的评论。无论如何,您没有任何逻辑可以找到每个
item标记。请尝试一下
标签: python csv xml-parsing