【问题标题】:attributes not appearing in xml2dict parse output even with xml_attribs = True即使使用 xml_attribs = True,属性也不会出现在 xml2dict 解析输出中
【发布时间】:2018-05-18 21:00:34
【问题描述】:

我在使用 python xmltodict 时遇到问题。遵循近乎共识的建议here,我尝试了 xmltodict 并非常喜欢它,直到我不得不访问处理程序顶层的属性。我可能做错了什么,但我不清楚是什么。我有一个看起来像这样的 xml 文档

<api>
<cons id="79550" modified_dt="1526652449">
<firstname>Mackenzie</firstname>
...
</cons>
<cons id="79551" modified_dt="1526652549">
<firstname>Joe</firstname>
...
</cons>
<api>

我用这个来解析它:

xmltodict.parse(apiResult.body, item_depth=2, item_callback=handler, xml_attribs=True)

其中apiResult.body 包含上面显示的xml。但是,尽管有 xml_attribs=True,但在处理程序中解析后,我在输出中看不到 @id@modified_dt,尽管原始中的所有 元素 都出现了。

处理程序编码如下:

def handler(_, cons):
    print (cons)
    mc = MatchChecker(cons)
    mc.check()
    return True

我可能做错了什么?

我也尝试过 xmljson 并且立即不喜欢它以及 xmltodict,只要我有办法解决这个问题。有没有人有解决这个问题的方法或可以更好地处理这个问题的包?

【问题讨论】:

    标签: python xml attributes xmltodict


    【解决方案1】:

    xmltodict 工作正常,但您正在解析参数 item_depth=2,这意味着您的处理程序将只能看到 &lt;cons&gt; 元素内的元素,而不是 &lt;cons&gt; 元素本身。

    xml = """
    <api>
    <cons id="79550" modified_dt="1526652449">
    <firstname>Mackenzie</firstname>
    </cons>
    </api>
    """
    
    def handler(_,arg):
        for i in arg.items():
            print(i)
        return True
    
    xmltodict.parse(xml, item_depth=2, item_callback=handler, xml_attribs=True)
    

    按预期打印('firstname', 'Mackenzie')

    鉴于:

    xmltodict.parse(xml, item_depth=1, item_callback=handler, xml_attribs=True)
    

    再次按预期打印('cons', OrderedDict([('@id', '79550'), ('@modified_dt', '1526652449'), ('firstname', 'Mackenzie')]))

    【讨论】:

    • 谢谢!我想这是有道理的,但是深度为 2 时,我能够以 d["firstname"] 的形式访问名字字段,正如我所期望的那样,但是深度为 1 时,我是否必须以 d 的形式访问它[“缺点”][“名字”]?
    • @SteveCohen 是的,没错,但它允许访问id,例如d["cons"]["@id"]
    • 不,这对我来说仍然没有意义。 depth 1 返回与 xml 中的 cons 元素相对应的深度 2 元素的 ARRAY。 id 在逻辑上与深度 2 元素相关联。当我在深度 1 工作时,即使我使用 d["cons']['firstname'] 语法,我也会收到“列表索引必须是整数,而不是 str”错误。我想我可以遍历处理程序中的列表,但我为什么必须这样做?深度 2 是我想要的,我仍然不明白为什么属性不显示。
    • 我认为这是 xmltodict 中的一个错误。我认为从它的代码来看,所有低于指定深度的深度级别都会自动将 xml_attribs 设置为 true(无论是否请求),但在请求的深度,xml_attribs 为 False。这就是为什么在我的例子中使用深度级别 1 来获取属性。在我的例子中,属性属于深度级别 2。
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多