HOWTO: Include XML in Another XML File

It is a common programming tool to include code from a separate file. Sometimes, this code is required to be included at a separate spot, and other times it can be included anywhere. However, the advantage of separating code and/or data into separate files is clear. When a change to code in one file is made, it is automatically applied to all instances where it is included.

It is plausible that we might have many XML files that should combine to make one master XML file, as each individual XML file may need to be manipulated by a program separately from the others. In this scenario, we would want our master XML file to be able to include these external files. We can accomplish this in XML with the ENTITY declaration. Let’s say we have the following two XML files:

GuessWho.xml

<guesswho>
   <person>
      <name>Herman</name>
      <gender>male</gender>
      <hair>
         <color>red</color>
         <bald>1</bald>
         <length>short</length>
         <hat>0</hat>
      </hair>
      <glasses>0</glasses>
      <eyes>brown</eyes>
      <nose>big</nose>
      <facial_hair />
      <lips>small</lips>
   </person>
</guesswho>

Claire.xml

<person>
   <name>Claire</name>
   <gender>female</gender>
   <hair>
      <color>red</color>
      <bald>0</bald>
      <length>medium</length>
      <hat>1</hat>
   </hair>
   <glasses>1</glasses>
   <eyes>brown</eyes>
   <nose>small</nose>
   <facial_hair />
   <lips>small</lips>
</person>

If we wanted to inject Claire.xml into the list of GuessWho.xml, we could add the following line:

<!ENTITY claire SYSTEM "Claire.xml">

The claire after the ENTITY declaration is the variable name of the entity. We use this variable name to insert the ENTITY at a later point in our XML file. SYSTEM defines the type of ENTITY, and the related parameter is the actual location of our XML file to include.

Once our ENTITY declaration is in place, we can reference it by placing an & in front of our variable name, i.e. &claire;.

Our final XML file will look like this:

updated GuessWho.xml

<!ENTITY claire SYSTEM "Claire.xml">
<guesswho>
   <person>
      <name>Herman</name>
      <gender>male</gender>
      <hair>
         <color>red</color>
         <bald>1</bald>
         <length>short</length>
         <hat>0</hat>
      </hair>
      <glasses>0</glasses>
      <eyes>brown</eyes>
      <nose>big</nose>
      <facial_hair />
      <lips>small</lips>
   </person>
&claire;
</guesswho>
Michael Marr
About Michael Marr
Michael Marr is a staff writer for WebProNews

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>