Skip to main content
 首页 » 编程设计

Python 和 ElementTree : How can I nest elements/subelements in an XML

2025年05月04日14davidwang456

背景

我正在使用 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])) 

这就是我存储来自表的信息的方式,这些表的唯一目的是连接来自其他 表的数据。 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_ 模式。 (如果我的术语听起来不对,请告诉我 - 数据库有时会让我感到困惑)。

请您参考如下方法:

当创建你的 Target 元素时(这里的问题中没有给出代码),确保你将它们要附加到的 sw_node 作为第一个传递争论。

即:

target_el = SubElement(sw_node, "Target") 

而不是...

target_el = SubElement(root_node, "Target") 

此类代码的典型模式可能具有以下外观(大致;需要一些测试,使用 pyformat paramstyle 为 DB-API 驱动程序编写,不适用于其他代码):

cursor = db.cursor() 
cursor.execute("SELECT * from SOFTWARE_") 
for sw_item in cursor.fetchall(): 
  sw_el = SubElement(root_el, 'Software') ## STORING THE ELEMENT HERE 
  sw_id = None 
  for idx in range(len(cursor.description)): 
    name = cursor.description[idx][0] 
    if name == 'id': 
      sw_id = sw_item[idx] 
    sw_el.attrib[name] = sw_item[idx] 
  ## QUERYING FOR CHILDREN HERE 
  cursor.execute("SELECT TARGET_.* 
                  FROM TARGET_, SOFTWARE_TARGET_ 
                  WHERE SOFTWARE_TARGET_.SOFTWARE1=%(sw_id)s 
                    AND SOFTWARE_TARGET_.TARGET2=TARGET_.ID", 
      sw_id=sw_id) 
  for target_item in cursor.fetchall(): 
    # create a new target element 
    target_el = SubElement(sw_el, 'Target') 
    # assign attributes to that element 
    for idx in range(len(cursor.description)): 
      name = cursor.description[idx][0].rsplit('.', 1)[-1] 
      target_el.attrib[name] = target_item[idx]