Creating Mixed-Content Elements

So far, the plain text in the documents we've looked at in this chapter has been confined to the deepest elements in the documentthat is, to elements that enclose no child elements, just text. However, as you know, you can also create elements that support mixed content both text and other elements. You can create mixed-content elements with schemas as well as DTDs. In these elements, character data can appear at the same level as child elements.

Here's an example document that shows what mixed-content elements look like using the elements we've declared in ch05_07.xsd. In this case, I'm creating a new element named <reminder> that encloses a reminder letter to a book borrower reminding him to return a book:

 <?xml version="1.0">  <reminder>     Dear <name>Britta Regensburg</name>:         The book <bookTitle>Snacking on Volcanoes</bookTitle>     was only supposed to be out for <maxDaysOut>14</maxDaysOut>     days. Please return it or pay     $<replacementValue>17.99</replacementValue>.     Thank you. </reminder> 

This document uses elements that we've defined before, character data, and the new <reminder> element. The <reminder> element is the one that has a mixed-content model; to declare it in a schema, I'll start by creating an anonymous new complex type like this inside the declaration for <reminder> . To indicate that this element can handle mixed content, you set the <complexType> element's mixed attribute to true :

 <xsd:element name="reminder">  <xsd:complexType mixed="true">   .   .   .   </xsd:complexType>  </xsd:element> 

Now all I have to do is to add the declarations for the elements that you can use inside the <reminder> element, like this:

 <xsd:element name="reminder">      <xsd:complexType mixed="true">  <xsd:sequence>   <xsd:element name="name" type="xsd:string"/>   <xsd:element name="bookTitle" type="xsd:string"/>   <xsd:element name="maxDaysOut">   <xsd:simpleType>   <xsd:restriction base="xsd:integer">   <xsd:maxExclusive value="14"/>   </xsd:restriction>   </xsd:simpleType>   </xsd:element>   <xsd:element name="replacementValue" type="xsd:decimal"/>   </xsd:sequence>  </xsd:complexType> </xsd:element> 

As you might recall from our discussion of DTDs, you can't constrain the order or number of child elements appearing in a mixed-model element. There's more power available when it comes to schemas, however: Here, the order and number of child elements does have to correspond to the order and number of child elements that you specify in the schema. In other words, even though DTDs provide only partial syntax specifications for mixed-content models, schemas provide much more complete syntax specifications.



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net