0

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?

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
Keith Sloan
  • 125
  • 1
  • 12
  • 1
    The answer to *How can I create/add the &materials;...* is here already: https://stackoverflow.com/a/60418151/407651. – mzjn Aug 29 '20 at 11:30
  • 1
    Duplicate of [creation of !ENTITY definition](https://stackoverflow.com/questions/60415435/creation-of-entity-definition) – Daniel Haley Aug 30 '20 at 03:31

1 Answers1

1

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>
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • Perhaps I was not CLEAR enough. I want to know how to create the &materials; – Keith Sloan Aug 28 '20 at 20:35
  • @KeithSloan - You were clear. My example does create the entity ref `&defines;`. Maybe my answer is not clear enough? I'll add a couple of line breaks so you can see the entity reference without scrolling. Maybe that will make it more clear. I'll also change `defines` to `materials` to also improve clarity. (I used the example entity declarations from one of your other questions and reduced it.) – Daniel Haley Aug 28 '20 at 20:37
  • Okay file now looks like <!ENTITY materials SYSTEM "materials.xml"> <!ENTITY solids SYSTEM "fred4-solids.xml"> <!ENTITY structure SYSTEM "fred4-structure.xml"> <!ENTITY setup SYSTEM "setup.xml"> ]> &define; &materials; &solids; &structure; – Keith Sloan Aug 29 '20 at 04:58
  • But I have a problem when I try and import, it does not seem to be expanding the entities despite the code being parser = etree.XMLParser(resolve_entities=True) root = etree.parse(filename, parser=parser) – Keith Sloan Aug 29 '20 at 05:01
  • @KeithSloan: The answer does explain how to create `&materials;`. If you have follow-up issues, please ask a new question. Also, it is very hard to read XML markup and code in comments. – mzjn Aug 29 '20 at 05:30
  • "Also, it is very hard to read XML markup and code in comments" Agreed that is why I also added code to initial query but it says will not be seen until a moderator okays it – Keith Sloan Aug 29 '20 at 07:19