DOM XML Python,检索特定数据

时间:2016-02-21 13:45:18

标签: python xml dom

我目前正在创建一个程序,它使用dom或minidom库从xml文档生成python中的报告。

我的程序当前从xml文件接收所有数据并将其打印出来。有没有办法让它只打印出xml文档的一个“部分”?

这是我到目前为止所拥有的...... 在此先感谢您的任何帮助

from xml.dom import minidom

doc = minidom.parse('crime.xml')


no = doc.getElementsByTagName("crime")

print("Please enter a Crim Id which you would like to produce a Report for:")
x = int(input("Enter a number: "))
print(x)# do something with x

for crime in no:
  crimeid = crime.getAttribute("id")
crimetype = crime.getAttribute("type")
victim = crime.getElementsByTagName("victim")[0]
address = crime.getElementsByTagName("address")[0]
witnesses = crime.getElementsByTagName("witnesses")[0]
suspects = crime.getElementsByTagName("suspects")[0]
description = crime.getElementsByTagName("description")[0]
charge = crime.getElementsByTagName("charge")[0]
print("id:%s, type:%s, victim:%s, address:%s, witnesses:%s, suspects:%s, description:%s, charge:%s" %(crimeid, crimetype, 
victim.firstChild.data, address.firstChild.data, witnesses.firstChild.data,
  suspects.firstChild.data, description.firstChild.data, charge.firstChild.data))

xml示例

<?xml version="1.0"?>

-<crimes>


-<crime type="vandalism" id="1001">
<victim>victim name</victim>
<address>some address</address>
-<info type="statements">
<victimStatement> sss </victimStatement>
<witnessStatement> sss </witnessStatement>
<suspectStatement> sss </suspectStatement>
</info>
<witnesses>suspect name</witnesses>
<suspects>suspect name</suspects>
<description>house window smashed</description>
<charge>£1234</charge>
</crime>

-<crime type="robbery" id="1002">
<victim>victim name</victim>
<address>some address</address>
-<info type="evidence">
<stolenitem> money </stolenitem>
<stolenvalue> £2000 </stolenvalue>
</info>
<witnesses>suspect name</witnesses>
<suspects>suspect name</suspects>
<description>theft of money</description>
<charge>£1234</charge>
</crime>

</crimes>

输出示例:

报道的犯罪:故意破坏

犯罪ID:1001

地址:某地址

(描述)房子窗户粉碎.....

受害者姓名

受害者陈述......

证人姓名

证人陈述......

可疑名称

怀疑声明......

结果费:1234英镑

1 个答案:

答案 0 :(得分:0)

首先,您的英镑符号应使用XML中的实体进行转换,以便格式良好,例如html entity func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { return cellOfType0; }else if indexPath.row == 1 { return cellOfType1; } ... } 。否则minidom会抱怨无效的令牌。要检索&#163;下的特定内容集,只需将循环调整为用户输入值:

<crime>