【问题标题】:Escaping python reserved words in xml attributes using the ElementTree library使用 ElementTree 库转义 xml 属性中的 python 保留字
【发布时间】:2017-07-13 18:52:42
【问题描述】:

我正在使用 ElementTree 库,并且我有一个 xml 标记,该标记具有一个名为“class”的键的属性。现在这显然是python中的保留字。任何人都知道如何逃避这一点,或者甚至有可能吗?

ownerNode = et.SubElement(rootNode, "Owner")
referenceNode = et.SubElement(ownerNode, class="org.identity", name="john")

^^^ 那么,如何转义上面的 class 关键字?

谢谢!

【问题讨论】:

    标签: python python-3.x elementtree


    【解决方案1】:

    基于the documentation,看起来你可以在字典中传递属性,键为字符串:

    referenceNode = et.SubElement(ownerNode, "refnode", {"class": "org.identity", "name": "john"})
    

    David Lambert 在讨论此问题的 python.org thread 中指出,对于仅接受关键字参数的函数 f,您可以这样做:

    def f(**kwargs):
        print(kwargs)
    
    f(**{'class':'sidebar'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 2015-05-03
      • 2021-12-14
      • 2011-05-27
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多