Search code examples
pythonxmllxmldtdxinclude

lxml and python: how to set "global" entities


I am using lxml to parse an xml file in python. The xml has the purpose of configuring my code. Since I need to use many different configurations which slightly differ, I am using the xi:include feature.

It would be really useful to be able to declare some entities in the "main" xml file and let the included ones to know about them. Here is my working example:

main.xml:

<?xml version="1.0"?>
<!DOCTYPE doc> 
<configuration xmlns:xi="http://www.w3.org/2001/XInclude" name="foo" version="0.1" >
 <xi:include href="./external.xml" />
</configuration>

external.xml:

<?xml version="1.0"?>
<!DOCTYPE doc [
       <!ENTITY bar "example">
       ]>
<objects>
   <object name="&bar;" />
</objects>

what I want to do is to declare bar inside main.xml, is it possible to do this? Thanks in advance, Matteo


Solution

  • This is not exactly the solution I was looking for, but kinda solved my problem:

    main.xml

    <?xml version="1.0"?>
    <!DOCTYPE doc>
    <configurations>
        <configuration>
        <xi:include href="./external/confs.xml" xpointer="xpointer(/ext/conf1)" />
        </configuration> 
    
        <configuration>
        <xi:include href="./external/confs.xml" xpointer="xpointer(/ext/conf2)" />
        </configuration> 
    </configurations>
    

    confs.xml

    <?xml version="1.0"?>
    <!DOCTYPE doc[
        <!ENTITY foo "bar">
    ]>
        <ext>
           <conf1>
               <inc name="apple_&foo;" />   
           </conf1>
    
           <conf2>
               <inc name="orange_&foo;" />
           </conf2>
    
        </ext>