python-3.xxmllxmlxml-entities

Creation of GDML include using python and lxml


According to the GDML manual I can include another file as follows enter image description here

How can I create/add the &materials; to the element using python and lxml?


Solution

  • You should be able to use etree.Entity...

    from lxml import etree
    
    docString = '<!DOCTYPE gdml [\n<!ENTITY materials SYSTEM "materials.xml">\n]>'
    
    NS = "http://www.w3.org/2001/XMLSchema-instance"
    location_attribute = f"{{{NS}}}noNameSpaceSchemaLocation"
    gdml = etree.Element("gdml",
                         attrib={location_attribute:
                                 "blahblahblah/gdml.xsd"})
    
    ent_ref = etree.Entity("materials")
    
    gdml.append(ent_ref)
    
    print(etree.tostring(gdml, doctype=docString).decode())
    

    prints...

    <!DOCTYPE gdml [
    <!ENTITY materials SYSTEM "materials.xml">
    ]>
    <gdml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:noNameSpaceSchemaLocation="blahblahblah/gdml.xsd">&materials;</gdml>