【发布时间】:2015-05-05 20:33:01
【问题描述】:
背景
我正在使用 Python 2.6、ElementTree 和 SQLite3。我的脚本目前执行以下操作:
- 连接到数据库以从表/模式中检索信息
- 将必要的数据添加到 XML 树中
- 输出一个(当前不正确的)XML 文件
代码
这是我检索架构数据并向 XML 添加元素的方式。我对SOFTWARE_ 和TARGET_ 表执行此操作。这是SOFTWARE_ 表:
software_attributes = ["id", "functionalDesignationHardware", "hwfin", "identname", "partnumber",
"repfin", "targetHardwareID"]
software = db.cursor().execute("SELECT %s from SOFTWARE_" % ", ".join([i + "_" for i in software_attributes]))
software_Data = software.fetchall()
ID1 = db.cursor().execute("SELECT id_ from SOFTWARE_")
software_IDs = ID1.fetchall()
for sw in software_Data:
sw_node = ET.SubElement(root, "Software")
for s in range(1, len(software_attributes)):
sw_node.set(software_attributes[s], str(sw[s]))
更新:这是我的 TARGET_ 表代码:
target_attributes = ["id", "functionalDesignationSoftware", "installscriptpathname", "ata", "status",
"swfin", "targetOSFC", "timestamp"]
target = db.cursor().execute("SELECT %s from TARGET_" % ", ".join([i + "_" for i in target_attributes]))
target_Data = target.fetchall()
ID2 = db.cursor().execute("SELECT id_ from TARGET_")
target_IDs = ID2.fetchall()
## CURRENTLY INCORRECT - only adds to the last created Software Element ##
for tg in target_Data:
tg_node = ET.SubElement(sw_node, "TargetModule")
for t in range(1, len(target_attributes)):
tg_node.set(target_attributes[t], str(tg[t]))
这就是我从表中存储信息的方式,这些表的唯一目的是连接 other 表中的数据。 SOFTWARE_TARGET_ 表将SOFTWARE_ 连接到TARGET_。我将其信息存储在字典中:
software_target = db.cursor().execute("SELECT SOFTWARE1, TARGET2 from SOFTWARE_TARGET_")
software_target_Data = software_target.fetchall()
# Map SOFTWARE1 to TARGET2
separated_st_Data = {}
for item in software_target_Data:
software1, target2 = item
try:
separated_st_Data[software1].append(target2)
except KeyError:
separated_st_Data[software1] = [target2]
尝试
到目前为止,我已经弄清楚了如何设置我的 xml 格式:
<Software attribute="stuff" attribute2="Stuff"/>
<Software attribute="stuff" attribute2="Stuff"/>
<Target attribute="things" attribute2="Things"/>
但我需要的是以下格式:
<Software attribute="stuff" attribute2="Stuff"
<Target attribute="things" attribute2="Things"/>
<Target attribute="things" attribute2="Things"/>
</Software>
<Software attribute="stuff" attribute2="Stuff"/>
哪个Target 子元素在哪个Software 元素之下由SOFTWARE_TARGET_ 表中的信息确定。我找到了如何遍历我的字典,如下所示:
depth=0
for k,v in sorted(separated_st_Data.items(),key=lambda x: x[0]):
if isinstance(v, dict):
print (" ")*depth + ("%s" % k)
walk_dict(v,depth+1)
else:
print (" ")*depth + "%s %s" % (k, v)
问题
如何根据数据库表中的信息创建格式正确的 XML 文件(如 Attemps 部分所述)?我创建了字典,认为我可以将它用于此目的 - 如果有必要,请告诉我。
备注
This 是我从SOFTWARE_TARGET_ 表创建的字典的样子。键表示来自SOFTWARE_ 的id_ 架构,值表示来自TARGET_ 的id_ 架构。 (如果我的术语听起来不对劲,请告诉我——数据库有时会让我感到困惑)。
【问题讨论】:
标签: python xml dictionary python-2.6 elementtree