Search code examples
xmldtdxml-validationdtd-parsing

Optional Element type DTD


i have an XML doc like this:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE school SYSTEM ""> 
<school> 
    <data> 
        <id>
            <uid>1</uid> 
        </id>
        <information>
            <name>Michael</name>
            <surename>Julius</surename>
        </information>
        <note> 
            <test>hans</test>

        </note> 
    </data> 
</school> 

and a DTD File

<!ELEMENT school (data)> 
<!ELEMENT data (id,information,note)> 
<!ELEMENT id (uid)> 
<!ELEMENT uid (#PCDATA)>
<!ELEMENT information (name,surename?)> 
<!ELEMENT name (#PCDATA)> 
<!ELEMENT surename (#PCDATA)> 
<!ELEMENT note (#PCDATA)>  <--- unknown element type

I want to define the <note> element with optional element types like

<note> 
  <test2>test2</test2>
</note>

or

<note>
  <unknown name></unknown name>
</note>

any help? thankz


Solution

  • You can use ANY in the element declaration for note. This will allow any element to be a child of note, but that element also has to be defined (have an element declaration). You can't have an undefined element.

    Example note declaration:

    <!ELEMENT note ANY>
    

    Example instance (the DTD can be external, but I used an internal subset because it was easier to test):

    <!DOCTYPE school [
    <!ELEMENT school (data)> 
    <!ELEMENT data (id,information,note)> 
    <!ELEMENT id (uid)> 
    <!ELEMENT uid (#PCDATA)>
    <!ELEMENT information (name,surename?)> 
    <!ELEMENT name (#PCDATA)> 
    <!ELEMENT surename (#PCDATA)> 
    <!ELEMENT note ANY>
    <!ELEMENT test2 (#PCDATA)><!--The element "test2" still has to be declared.-->
    ]> 
    <school> 
        <data> 
            <id>
                <uid>1</uid> 
            </id>
            <information>
                <name>Michael</name>
                <surename>Julius</surename>
            </information>
            <note> 
                <test2>hans</test2>         
            </note> 
        </data> 
    </school>