使用Python提取xml数据

时间:2018-11-27 10:11:30

标签: python xml python-3.x

我是xml文件的新手,我正尝试使用“ ElementTree”读取xml文件,如下所示:

import xml.etree.ElementTree as ET
tree = ET.parse('/users/user/file.xml')
root = tree.getroot()
a= [elem.tag for elem in root.iter()]

使用上面的代码,我可以返回xml文件中存在的列的列表。我被卡住了,我正在尝试执行以下操作:

  1. 如何获取与各列对应的值
  2. 遍历整个文件以读取xml文件的内容。

任何人都可以建议我如何继续前进。谢谢。

样本数据:

<?xml version="1.0" encoding="UTF-8"?><Sales>
  <Sale>
    <Action>new</Action>
    <bill>46610272</bill>
    <prod_id/>
    <prod_name>
      <prod_cat/>
      <code>XYZ</code>
     </prod_name>
    <comments>
     </Sale>
 <Sale>
<Action>new</Action>
<bill>54465334</bill>
<prod_id/>
<prod_name>
  <prod_cat/>
  <code>ABC</code>
</prod_name>
<comments>
 </Sale>

预期输出:

Action,Bill,prod_id,prod_name,prod_cat,code,comments
new, 46610272,,,,XYZ,
new, 54465334,,,,XYZ,

0 个答案:

没有答案