Search code examples
xmlcode-duplication

Duplicate some parts of XML without rewriting them


I have an XML file with duplicate parts such as:

<argument name="create">
    <argument name="user" type="text"></argument>
    <argument name="password" type="password"></argument>
    (and so on)
</argument>

<argument name="update">
    <argument name="user" type="text"></argument>
    <argument name="password" type="password"></argument>
    (and so on)
</argument>

I would like to have the part between create and update declared once then append it between create and update with a one-liner. This would save me a lot of lines.

Any way to do that in XML?


Solution

  • You can use SGML/XML"entities" for that, which can contain replacement text or markup for reuse at multiple places:

    <!DOCTYPE arguments [
      <!ENTITY user-and-password
       '<argument name="user" type="text"/>
        <argument name="password" type="password"/>'>
    ]>
    <arguments>
      <argument name="create">
        &user-and-password;
      </argument>
      <argument name="update">
        &user-and-password;
      </argument>
    </arguments>
    

    Note that you have to adapt the DOCTYPE: it must match the document element of your XML.

    See also XML configuration inheritance, avoid duplications