Search code examples
xmldtd

DTD for elements inside an element


I need a DTD for validating an XML document like this:

<recipes>
     <recipe>
          <difficulty>2</difficulty>
          <people>4</people>
          <procedure>Break an egg and fry it</procedure>
          <ingredients>
               <ingredient>Egg</ingredient>
               <ingredient>...</ingredient>
          </ingredients>
     </recipe>
     ...
</recipes>

This is my DTD:

<!ELEMENT recipe(difficulty, people, procedure)>
<!ELEMENT difficulty #PCDATA>
<!ELEMENT people #PCDATA>
<!ELEMENT procedure #PCDATA>

which does not allow to declare <ingredients> element so that XML document would not be validated. How can I modify my DTD in order to achieve my goal?

My idea is:

<!ELEMENT recipe(difficulty, people, procedure, ingredients)>
<!ELEMENT difficulty #PCDATA>
<!ELEMENT people #PCDATA>
<!ELEMENT procedure #PCDATA>

<!ELEMENT ingredients(ingredient)>
<!ELEMENT ingredient #PCDATA>

but I am not sure this is the correct solution.


Solution

  • You use the + operator to indicate, that you can have multiple elements of the same name inside another element. In this case it looks like this:

    <!ELEMENT ingredients (ingredient+)>
    <!ELEMENT ingredient (#PCDATA)>
    

    The full DTD can look like this:

    <!ELEMENT recipes (recipe+)>
    <!ELEMENT recipe (difficulty, people, procedure, ingredients)>
    <!ELEMENT difficulty (#PCDATA)>
    <!ELEMENT people (#PCDATA)>
    <!ELEMENT procedure (#PCDATA)>
    <!ELEMENT ingredients (ingredient+)>
    <!ELEMENT ingredient (#PCDATA)>