提取XML属性

时间:2013-01-30 07:32:25

标签: python xml python-3.x beautifulsoup

我有一个XML文件,其中包含数千条记录:

<custs>
    <record cust_ID="B123456@Y1996" l_name="Jungle" f_name="George" m_name="OfThe" city="Fairbanks" zip="00010" current="1" />
    <record cust_ID="Q975697@Z2000" l_name="Freely" f_name="I" m_name="P" city="Yellow River" zip="03010" current="1" />
    <record cust_ID="M7803@J2323" l_name="Jungle" f_name="Jim" m_name="" city="Fallen Arches" zip="07008" current="0" />
</custs>
    #   (I know it's not normalized.  This is just sample data)

如何将其转换为CSV或制表符分隔文件?我知道我可以使用re.compile()语句在Python中对其进行硬编码,但是在diff XML文件布局中必须有更简单,更便携的东西。

我在这里发现了一些关于attribs的帖子,(Beautifulsoup unable to extract data using attrs=classExtracting an attribute value with beautifulsoup)他们几乎让我在那里:

#  Python 3.30
#
from bs4 import BeautifulSoup
import fileinput

Input = open("C:/Python/XML Tut/MinGrp.xml", encoding = "utf-8", errors = "backslashreplace")
OutFile = open('C:/Python/XML Tut/MinGrp_Out.ttxt', 'w', encoding = "utf-8", errors = "backslashreplace")

soup = BeautifulSoup(Input, features="xml")

results = soup.findAll('custs', attrs={})

# output = results   [0]#[0]

for each_tag in results:
    cust_attrb_value = results[0]
#       print (cust_attrb_value)
    OutFile.write(cust_attrb_value)

OutFile.close()

下一步(最后?)步骤是什么?

2 个答案:

答案 0 :(得分:2)

如果此数据格式正确 - 例如,使用规范XML - 您应该考虑lxml而不是BeautifulSoup。使用lxml,您可以读取文件,然后可以在其上应用DOM逻辑,包括XPath查询。使用XPath查询,您可以获得代表您感兴趣的每个节点的lxml个对象,从中提取您需要的数据,并使用类似的方式将它们重写为您选择的任意格式。 csv模块..

具体来说,在lxml文档中,请查看以下教程:

答案 1 :(得分:1)

我(也)不会使用BeautifulSoup,虽然我喜欢lxml,但这是一个额外的安装,如果你不想打扰,这很简单,可以使用标准的lib ElementTree模块。< / p>

类似的东西:

import xml.etree.ElementTree as ET
import sys
tree=ET.parse( 'test.xml' )
root=tree.getroot()
rs=root.getchildren()
keys = rs[0].attrib.keys()
for a in keys: sys.stdout.write(a); sys.stdout.write('\t')
sys.stdout.write('\n')
for r in rs:
    assert keys == r.attrib.keys()
    for k in keys: sys.stdout.write( r.attrib[k]); sys.stdout.write('\t')
    sys.stdout.write('\n')

将从python-3生成:

zip m_name  current city    cust_ID l_name  f_name  
00010   OfThe   1   Fairbanks   B123456@Y1996   Jungle  George  
03010   P   1   Yellow River    Q975697@Z2000   Freely  I   
07008       0   Fallen Arches   M7803@J2323 Jungle  Jim 

请注意,使用Python-2.7,属性的顺序会有所不同。 如果您希望它们以不同的特定顺序输出,您应该排序或 订购列表“键”。

断言检查所有行是否具有相同的属性。 如果元素中实际上缺少或有不同的属性, 那么你将不得不删除它并添加一些代码来处理差异 并提供缺失值的默认值。 (在您的示例数据中,您有一个 空值(m_name =“”),而不是缺失值。你可能想检查一下 这种情况由此输出的消费者处理好,或者添加一些 对这种情况更特殊的处理。

相关问题