How to add a namespace to an attribute in lxml

前端 未结 2 1432
别跟我提以往
别跟我提以往 2021-01-04 03:15

I\'m trying to create an xml entry that looks like this using python and lxml:


<
相关标签:
2条回答
  • 2021-01-04 04:06

    Try this:

    builder = ElementMaker(namespace="http://a.different.url/blah/v.10",
                           nsmap={
                             'adlcp': "http://a.namespace.url/blah/v.10",
                             'anotherns': "http://a.different.url/blah/v.10"
                           })
    
    builder.resource()
    builder.attrib['href'] = "Unit 4.html"
    builder.attrib['{http://a.namespace.url/blah/v.10}scormtype'] = 'sco'
    
    print(etree.tostring(builder, pretty_print=True))
    
    0 讨论(0)
  • 2021-01-04 04:08

    This is not a full reply but just a few pointers.

    adlcp is not the namespace it is a namespace prefix. The namespace is defined in the document by an attribute like xmlns:adlcp="http://xxx/yy/zzz"

    In lxml you always set an element/attribute name including the namespace e.g. {http://xxx/yy/zzz}scormtype instead of just scormtype. lxml will then put in a namespace prefix automatically. However lxml will set the prefix to ns0 or similar unless you do more fiddling but that should be sufficient as the prefix does not mean anything. (However some people prefer controlling the prefix name; see the nsmap argument on the Element and SubElement functions, and the register_namespace function).

    I would look at the lxml tutorial on namespace and also Dive into Python - XML chapter

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