lxml tag name with a “:”

后端 未结 1 785
南旧
南旧 2021-01-12 07:41

I am trying to create an xml tree from a JSON object using lxml.etree. Some of the tagnames contin a colon in them something like :-

\'settings:current\' I tried usi

相关标签:
1条回答
  • 2021-01-12 08:29

    Yes, first read and understand XML namespaces. Then use that to generate XML-tree with namespaces:u

    >>> MY_NAMESPACES={'settings': 'http://example.com/url-for-settings-namespace'}
    >>> e=etree.Element('{%s}current' % MY_NAMESPACES['settings'], nsmap=MY_NAMESPACES)
    >>> etree.tostring(e)
    '<settings:current xmlns:settings="http://example.com/url-for-settings-namespace"/>'
    

    And you can combine that with default namespaces

    >>> MY_NAMESPACES={'settings': 'http://example.com/url-for-settings-namespace', None:    'http://example.com/url-for-default-namespace'}
    >>> r=etree.Element('my-root', nsmap=MY_NAMESPACES)
    >>> d=etree.Element('{%s}some-element' % MY_NAMESPACES[None])
    >>> e=etree.Element('{%s}current' % MY_NAMESPACES['settings'])
    >>> d.append(e)
    >>> r.append(d)
    >>> etree.tostring(r)
    '<my-root xmlns:settings="http://example.com/url-for-settings-namespace" xmlns="http://example.com/url-for-default-namespace"><some-element><settings:current/></some-element></my-root>'
    

    Note, that you have to have an element with nsmap=MY_NAMESPACES in your XML-tree hierarchy. Then all descendand nodes can use that declaration. In your case, you have no that bit, so lxml generates namespaces names like ns0

    Also, when you create a new node use namespace URI for tag name, not namespace name: {http://example.com/url-for-settings-namespace}current

    0 讨论(0)
提交回复
热议问题