boxy
boxy

Reputation: 139

DTD and XML examples

here is my DTD rules should have following property: book have a title, release year, one or more author , one or more rating (0-5), any number of reviews.

<!ELEMENT books (book+)>
<!ELEMENT book (title, author+,year,rating+,review*)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT rating (0|1|2|3|4|5)>
<!ELEMENT review (#PCDATA)>

and here is my example XML:

 <?xml version="1.0" standalone="no" ?>
 <!DOCTYPE books SYSTEM "books.dtd">
<books>
    <book>
      <title>book1</title>
      <author>bob</author>
      <year>2000</year>
      <rating>2</rating>
      <rating>3</rating>
    </book>
    <book>
     <title>book2</title>
     <author>alice</author>
     <year>2001</year>
     <rating>4</rating>
     <rating>5</rating>
    </book>
    <book>
     <title>book3</title>
     <author>john</author>
     <year>2002</year>
     <rating>5</rating>
     <rating>0</rating>
     <review>not bad</review>
    </book>
</books>

but I always get this error enter image description here.

Upvotes: 3

Views: 2714

Answers (1)

potame
potame

Reputation: 7905

<!ELEMENT rating (0|1|2|3|4|5)> is not correct in DTDs and regarding your XML. It means that you would want the rating element to contain either an element named "0" (<0>), or "1", "2", and so on. Unfortunately, a tag name can't begin with a number.

To achieve what you want to do is commonly done with an attribute. Declare the rating element as empty, with an attribute to be selected among a value in a list like so:

<!ELEMENT rating EMPTY>
<!ATTLIST rating
          rank  (0|1|2|3|4|5)   #REQUIRED  >

and your XML instance will become:

<?xml version="1.0" standalone="no" ?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
    <book>
      <title>book1</title>
      <author>bob</author>
      <year>2000</year>
      <rating rank="2" />
      <rating rank="3" />
    </book>
    <book>
     <title>book2</title>
     <author>alice</author>
     <year>2001</year>
     <rating rank="4" />
     <rating rank="5" />
    </book>
    <book>
     <title>book3</title>
     <author>john</author>
     <year>2002</year>
     <rating rank="5 />
     <rating rank="0" />
     <review>not bad</review>
    </book>
</books>

If you really want the rating to be set as textual content, it is not possible to constraint its value with a DTD, however it is possible with XML Schema.

Upvotes: 3

Related Questions