将XML解析为列表字典Python/Djang

2024-09-30 06:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python解析xml时遇到了一个小问题。我想让我的字典看起来像下面这样

listDict = [{'name':'Sales','id':'1','position':'1','order_by_type':'True','order_by_asc':'True;}, {'name':'Information','id':'2','position':'1','order_by_type':'True','order_by_asc':'True;}]

我认为从xml字符串中提取数据后的循环是错误的。在

^{pr2}$

这将产生以下结果。在

instance = {0: ['Sales 2', '1', '10', 'True', 'True'], 1: ['Information 2', '2', '20', 'True', 'True'], 2: ['Listing 2', '3', '30', 'True', 'True'], 3: ['Information', '4', '40', 'True', 'True'], 4: ['Land', '5', '50', 'True', 'True'], 5: ['&', '6', '60', 'True', 'True'], 6: ['Tax', '7', '70', 'True', 'True'], 7: ['Construction', '9', '90', 'True', 'True'], 8: ['Interior/Utilites', '10', '100', 'True', 'True'], 9: ['HOA/Community', '11', '110', 'True', 'True'], 10: ['Remarks', '12', '120', 'True', 'True'], 11: ['Exterior', '8', '80', 'True', 'True']}) 

我的最终目标是能够在我的django模板上执行以下操作

{%for item in instance%}
{{ item.name }}
{% endfor %}

任何关于我可能会出问题的帮助都会很有帮助。提前谢谢你的帮助。在

编辑: 如我所问,这是我拥有的xml。在

    <?xml version="1.0" ?>
<FormInstance>
    <BaseCategory>
        <Name>Sales</Name>
        <base_id>1</base_id>
        <position>10</position>
        <order_by_type>True</order_by_type>
        <order_by_asc>True</order_by_asc>
    </BaseCategory>
    <BaseCategory>
        <Name>Information</Name>
        <base_id>2</base_id>
        <position>20</position>
        <order_by_type>True</order_by_type>
        <order_by_asc>True</order_by_asc>
        <MainCategory>
            <main_id>1</main_id>
            <Name>Address 3</Name>
            <is_visible>True</is_visible>
            <position>10</position>
            <order_by_type>True</order_by_type>
            <order_by_asc>True</order_by_asc>
            <SubCategory>
                <sub_id>1</sub_id>
                <Name>Street Number 2</Name>
                <sub_library_id>StreetNumber</sub_library_id>
                <field_display_type>[u'input']</field_display_type>
                <field_type>[u'varchar']</field_type>
                <is_active>True</is_active>
                <is_required>True</is_required>
                <help_text>Street Number</help_text>
                <main_category>1</main_category>
                <is_visible>True</is_visible>
                <position>10</position>
                <order_by_type>True</order_by_type>
                <order_by_asc>True</order_by_asc>
                <show_seller>True</show_seller>
                <Enumerations>
                    <enum_id>4</enum_id>
                    <Name>Test Enum</Name>
                    <library_id>test enum</library_id>
                    <is_active>True</is_active>
                    <sub_category>1</sub_category>
                    <is_visible>True</is_visible>
                    <position>10</position>
                    <order_by_type>True</order_by_type>
                    <order_by_asc>True</order_by_asc>
                </Enumerations>
            </SubCategory>
        </MainCategory>
    </BaseCategory>
</FormInstance>

Tags: nameidtruebasebyinformationismain
1条回答
网友
1楼 · 发布于 2024-09-30 06:23:00

所以,根据我在预期结果中收集到的信息,看起来您只想获得严格BaseCategory的节点的信息,对吗?在编辑中提供的XML中,有两个。

您应该将XML看作一个节点树。在本例中,您有如下内容:

                     FormInstance  # this is the root
                      /         \
                     /           \
             BaseCategory       BaseCategory
             (name:Sales)    (name:Information)
                                    \
                                     \
                                  MainCategory
                                (name:Address 3)
                                        \
                                         \
                                      Subcategory
                                  (name:Street Number 2)

但是您只需要BaseCategory元素中的信息,对吗?

你可以把自己放在root(这。。。好。。。遍历它的BaseCategory节点,从这些BaseCategory节点获取所需的项,并将它们放入字典列表中。

比如:

^{pr2}$

哪些输出:

Found 2 base_categories.
list_dict=[{'id': 1,
  'name': 'Sales',
  'order_by_asc': True,
  'order_by_type': True,
  'position': 10},
 {'id': 2,
  'name': 'Information',
  'order_by_asc': True,
  'order_by_type': True,
  'position': 20}]

其思想是,一个BaseCategory项可以被看作是一个自包含的记录(比如一个dict,如果它有助于您看到它的话),它可以包含(在其中)以下属性:

  • 名称在Name中的字符串
  • base_id中的数字标识
  • 一个数字position
  • 布尔值order_by_type
  • 布尔值order_by_asc
  • 另一个对象MainCategory具有自己的字段。。。在

因此,每当您在这些BaseCategory节点中定位自己时,您只需收集其中的有趣字段并将它们放入字典中。

当您这样做时:

^{4}$

您将这些元素(base_idposition…)几乎视为独立的元素,这并不完全是XML中的元素。

但是,如果您绝对确定所有这些列表(base_catsbase_cats_idbase_position…)确实包含相同数量的条目,那么您仍然可以使用其中一个列表的长度重新构建字典(在下面的示例中len(base_cats),但它可能是len(base_cats_id)len(base_position)。。。因为所有这些列表具有相同的长度)在同一步骤中迭代所有列表:

base_cats = xml_data.findall('./BaseCategory/Name')
base_cats_id = xml_data.findall('./BaseCategory/base_id')
base_postion = xml_data.findall('./BaseCategory/position')
base_order_by_type = xml_data.findall('./BaseCategory/order_by_type')
base_order_by_asc = xml_data.findall('./BaseCategory/order_by_asc')

list_dict = []
for i in range(len(base_cats)):
    list_dict.append({
        "name": base_cats[i].text,
        "id": int(base_cats_id[i].text),
        "position": int(base_postion[i].text),
        "order_by_type": True if base_order_by_type[i].text.lower() == "true" else False,
        "order_by_asc": True if base_order_by_asc[i].text.lower() == "true" else False,
    })
print("list_dict=%s" % (pprint.pformat(list_dict)))

相关问题 更多 >

    热门问题