【问题标题】:When using lxml, can the XML be rendered without namespace attributes?使用 lxml 时,是否可以在没有命名空间属性的情况下呈现 XML?
【发布时间】:2011-02-22 22:23:47
【问题描述】:

我正在使用 lxml 生成一些 XML 并生成如下所示的节点:

<QBXML xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
py:pytype="TREE">

和:

<MaxReturned py:pytype="int">

这些自定义属性正在扼杀 Quickbooks 的解析器。我可以在没有自定义内容的情况下让 LXML 呈现吗?

【问题讨论】:

    标签: python lxml


    【解决方案1】:

    看起来像下面的照顾它:

    objectify.deannotate(root, xsi_nil=True)
    etree.cleanup_namespaces(root)
    

    或者,如果使用 lxml >= 2.3.2(感谢@Pedru):

    objectify.deannotate(root, cleanup_namespaces=True, xsi_nil=True)
    

    【讨论】:

    • 从 lxml 版本 2.3.2 你可以将cleanup_namespaces=True 传递给objectify.deannotate()(无需调用etree.cleanup_namespaces()
    【解决方案2】:

    如果你想要嵌套的 XML,你可以这样做:

    from lxml import objectify
    doc = objectify.ElementMaker(annotate=False)
    doc = (objectify.E.configuration(getattr(objectify.E,'networklists'),name="acl.conf",description="Network Lists"))
    objectify.deannotate(doc,cleanup_namespaces=True)
    

    自定义属性的输出是这样的:

    <configuration description="Network Lists" name="acl.conf">
    <network-lists>
    
    </network-lists>
    </configuration>
    

    【讨论】:

      【解决方案3】:

      如果你正在使用

      etree.fromstring(xml_response)
      

      然后这样做:

      xml_response.replace(' xmlns:', ' xmlnamespace:').replace(' xmlns=', ' xmlnamespace=')
      

      避免它解析命名空间

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-03
        相关资源
        最近更新 更多