A

Answers to Exercises

CHAPTER 1 ANSWERS TO EXERCISES

Exercise 1 Solution

A sample document, now element-centric, is shown here:

<applicationUsers>
  <user>
    <firstName>Joe</firstName>
    <middleName>John</middleName>
    <lastName>Fawcett</lastName>
  </user>
  <user>
    <firstName>Danny</firstName>
    <middleName>John</middleName>
    <lastName>Ayers</lastName>
  </user>
  <user>
    <firstName>Catherine</firstName>
    <middleName>Elizabeth</middleName>
    <lastName>Middleton</lastName>
  </user>
</applicationUsers>

Exercise 2 Solution

The main disadvantage is that the size of the file is greatly increased. In general, each additional user needs an extra 72 bytes, compared to the original version. For a small number of users this probably won’t matter, but with a large number, or if you are transmitting many of these files, this could mean much more network traffic, leading to higher costs and reduced efficiency. This is one reason that, when designing an XML format for your data, it is recommended to choose attributes unless you have good reason not to.

CHAPTER 2 ANSWERS TO EXERCISES

Exercise 1 Solution

There are four errors altogether:

  • <xmlLibrary> is wrong as element names cannot begin with the letters XML whether uppercase or lowercase.
  • publicationYear=1898 is incorrect as all attribute values must be quoted, whether or not they contain spaces.
  • <title> Arms & The Man</title> is using a forbidden character, &, which needs be replaced with a entity reference, &amp;.
  • <play description> is illegal as it contains a space in the element name.

A corrected version of the file could look like this:

<library>
  <play publicationYear=”1898”>
    <title>Arms &amp; The Man</title>
    <author>George Bernard Shaw</author>
    <playDescription>Comedy dealing with the futility of war
 and the hypocrisy of human nature.</playDescription>
  <play>
  <play publicationYear=”1950”>
    <title>The Mousetrap</title>
    <author>Agatha Christie</author>
    <playDescription>A traditional whodunnit
 with an extraordinary twist.</playDescription>
  <play>
</library>

Exercise 2 Solution

An example of declaring an entity reference for an e-mail address is shown in the following snippet which first declares the reference in a document type definition and then uses it by surrounding the name of it, email, with an ampersand (&) and a semi-colon (;):

<!DOCTYPE data [
  <!ENTITY email “[email protected]”>
]>
<data>Entity reference example to insert my email: &email;</data>

CHAPTER 3 ANSWERS TO EXERCISES

Exercise 1 Solution

The three mistakes are:

  • The xmlData prefix is used on the <document> element before it is declared.
  • Prefixes beginning with xml are not allowed.
  • The ns prefix is used on the <details> element without being declared.

The corrected document is shown in the following snippet:

image <data:document xmlns:ns=”http://www.wrox.com/chapter3/exercise1/ns”
               xmlns:data=”http://www.wrox.com/chapter3/exercise1/data”>
  <data:item>
    <ns:details>There's nothing wrong with this document?</ns:details>
  </data:item>  
</data:document>

Exercise1-answer.xml

Exercise 2 Solution

The three errors are:

  • You presumably don’t control the wrox.com domain; instead you should choose a domain you do control or have permission to use, for example the company that you work for.
  • It is not good practice to have spaces in a namespace URI.
  • Problems can arise when using escaped characters, in this instance %7e. This corresponds to the ∼ character but namespaces are compared on the literal string. This means that often, due to the vagaries of software support for escaped characters, you’ll see two namespace URIs which appear identical but aren’t. Assuming you work for example.com a better URI would be:
    http://www.example.com/namespaces/HRapplication/~config

CHAPTER 4 ANSWERS TO EXERCISES

Exercise 1 Solution

Your solution should look very much like the examples already in the document, in following the form:

  <contact person=”Your Name” tags=”whatever tags you chose”>
  ...
  </contact>

Exercise 2 Solution

In any document valid to your DTD, the contact element will now contain the extra gender attribute, like this:

  <contact person=”Joe_Fawcett” tags=”author xml poetry” gender=”male”>
...
</contact>

To support this, your DTD will now include the following new line:

<!ATTLIST contact gender (male | female) #REQUIRED>

Exercise 3 Solution

To specify that each contact has zero or more phone numbers, you need to provide a cardinality indicator. In Table 4-1 you can see that the ∗ character is used for “zero or more.” The phone numbers are given in the XML documents using the <phone> element, but the cardinality is specified in that element’s parent, leading to the result:

<!ELEMENT contact (name, location, phone∗, knows, description)>

Extending the DTD to include website and email elements is a matter of first of adding these to the declaration of their parent element, <contact>, like so:

<!ELEMENT contact (name, location, phone∗, knows, description, website, email)>

Then you should have described what kind of content these elements should support.

<!ELEMENT website (#PCDATA)>
<!ELEMENT email (#PCDATA)>

These elements are probably good candidates for using cardinality constraints, so for example if you wanted to specify that each contact should have one or more e-mail addresses, but zero or more websites, the declaration for the <contact> element would now look like this:

<!ELEMENT contact (name, location, phone∗, knows, description, website∗, email+)>

CHAPTER 5 ANSWERS TO EXERCISES

Exercise 1 Solution

One possible approach to adding the gender attribute is to define the type separately in the document. After the line:

<attribute name=”person” type=”ID”/>

you can add:

<attribute name=”gender” type=”GenderType” use=”required”/>

Note the use attribute, ensuring a value is provided. Then for the definition itself:

  <simpleType name=”GenderType”>
            <restriction base=”string”>
              <enumeration value=”male”/>
              <enumeration value=”female”/>
            </restriction>
  </simpleType>

Exercise 2 Solution

To support one or more phone numbers, it’s enough to add appropriate cardinality attributes to the phone element:

<element name=”phone” type=”contacts:PhoneType” minOccurs=”0” maxOccurs=”unbounded”/>

Exercise 3 Solution

The solution to this problem follows the requirements fairly literally, leading to this:

  <complexType>
 
      <sequence maxOccurs=”unbounded”>
 
         <any processContents=”lax” 
                 namespace=”http://www.w3.org/1999/xhtml” />
 
      </sequence>
 
   </complexType>

Remember that <any> cannot be placed directly inside an <complexType>. You need a container like a sequence or choice.

CHAPTER 6 ANSWERS TO EXERCISES

Exercise 1 Solution

If you want to use the XML based syntax then you first need to add a reference to the XML Schema data type library on the <element> element like so:

<element xmlns=”http://relaxng.org/ns/structure/1.0” name=”library”
         datatypeLibrary=”http://www.w3.org/2001/XMLSchema-datatypes”>

You can then add the actual attribute with its data type, and wrap it in an <optional> element as follows:

<element xmlns=”http://relaxng.org/ns/structure/1.0” name=”library”
         datatypeLibrary=”http://www.w3.org/2001/XMLSchema-datatypes”>
    <oneOrMore>
        <element name=”book”>
            <attribute name=”id”/>
            <attribute name=”publishedDate”/>
            <attribute name=”genre”/>
            <optional>
              <attribute name=”url”>
                <data type=”anyURI” />
              </attribute>
            </optional>
            <element name=”title”>
                <text/>
            </element>

If you choose to use the compact syntax then you don’t need to declare the data type library because XML Schema types are already bound to the xsd prefix. You just need to declare the attribute with its data type, and follow it with a question mark to make it optional, as shown here:

element library {
  element book {
    attribute id { text},
    attribute publishedDate { text },
    attribute genre { text },
    attribute url { xsd:anyURI }?,
    element title { text },
    element authors {
      attribute count { text },
      element author {
        attribute id { text },
        text
      }+ 
    },
    element characters {
      element character {
        attribute id { text },
        element name { text },
        element description { text }
      }∗
    },  
    element description { text }?
  }+
}

Exercise 2 Solution

Add an <xs:annotation> element containing an <xs:appinfo> element to hold the Schematron rule. The rule’s context is set to character and then you can use XPath’s string-length() function to compare the two values:

<xs:element name=”characterDescriptionLength”>
    <xs:annotation>
      <xs:appinfo>
        <sch:pattern id=”character”>
          <sch:rule context=”character”>
            <sch:assert test=”string-length(description) &gt;
 string-length(name)”>The character's description must be
 longer than their name.</sch:assert>
          </sch:rule>
        </sch:pattern>
      </xs:appinfo>
    </xs:annotation>

CHAPTER 7 ANSWERS TO EXERCISES

Exercise 1 Solution

//entry[.//born]

Recall that // is short for descendant (in effect), so that .//born evaluates to a list of all <born> elements anywhere under the current node and at the start of the expression // means the root element or any child or descendent of the root element.

Exercise 2 Solution

It returns all <div> elements that are the first child of their parent, anywhere inside the <body> element that’s the child of the outermost element, <html> in this case.

It may return more than one node. An incorrect answer might be that it returns the first <div> element in the document; it doesn’t do that.

Exercise 3 Solution

//div[not(@id)] 

CHAPTER 8 ANSWERS TO EXERCISES

Exercise 1 Solution

Choose three from the following:

  • generate-id(): Generates a unique ID for a node.
  • last(): Gives the size of the context.
  • position(): Gives a nodes position in the context.
  • system-property(): Used to discover various system properties. For example: system-property(“xsl:version”) gives the version of XSLT the processor supports such as 2.0.
  • key(): Returns a node based on a predefined key declared with the <xsl:key> element.
  • function-available(): Tests whether a function, whose name is passed in as a string, is available to be used.

There are plenty more; see the XSLT specifications at www.w3.org/TR/xslt20 for full details.

Exercise 2 Solution

First you’ll need an external document to represent the currency rates; this should be created via a web service but for this example it’s just a hard-coded list of values like so:

image <conversions>
  <conversion from=”USD” to=”GBP” rate=”0.625195374”/>
  <conversion from=”GBP” to=”USD” rate=”1.5995” />
  <conversion from=”USD” to=”EUR” rate=”0.75001875” />
  <conversion from=”EUR” to=”USD” rate=”1.3333” />
  <conversion from=”GBP” to=”EUR” rate=”1.19965499” />
  <conversion from=”EUR” to=”GBP” rate=”0.833572992” />
 </conversions>

ConversionRates.xml

The actual stylesheet has three <xsl:param> elements to represent the currency that you are converting from, the currency you are converting to, and the amount to convert. These all have defaults specified as shown here.

image <?xml version=”1.0” encoding=”utf-8”?>
<xsl:stylesheet version=”2.0”
                xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
                xmlns:xs=”http://www.w3.org/2001/XMLSchema”
                exclude-result-prefixes=”xs”>
 
  <xsl:output indent=”yes” />
 
  <xsl:param name=”currencyFrom” select=”'USD'” as=”xs:string” />
  <xsl:param name=”currencyTo” select=”'GBP'” as=”xs:string” />
  <xsl:param name=”amountToConvert” select=”1” as=”xs:decimal”/>
  <xsl:variable name=”conversionRates”
       select=”document('conversionrates.xml')/∗” />
  
  <xsl:template name=”main”>
    <xsl:variable name=”rate” select=
“$conversionRates/conversion
[@from = $currencyFrom and @to = $currencyTo]/@rate” />
    <conversion>
      <from><xsl:value-of select=”$currencyFrom” /></from>
      <to><xsl:value-of select=”$currencyTo” /></to>
      <amountToConvert>
  <xsl:value-of select=”$amountToConvert” /></amountToConvert>
      <rate><xsl:value-of select=”$rate” /></rate>
      <convertedAmount>
  <xsl:value-of select=”$amountToConvert ∗ $rate” /></convertedAmount>
    </conversion>
  </xsl:template>
</xsl:stylesheet>

CurrencyConvertor.xslt

The document() function is used to access the conversion rates and then the individual <conversion> element is chosen by matching its from and to attributes. Finally the full details are output, including the converted amount that is found by multiplying the input amount by newly acquired $rate.

You can test this code by using one of the following command lines:

java net.sf.saxon.Transform -s:CurrencyConvertor.xslt -it:main
  currencyFrom=GBP currencyTo=EUR amountToConvert=100

or

Transform -s:CurrencyConvertor.xslt -it:main
  currencyFrom=GBP currencyTo=EUR amountToConvert=100

You should see the following output:

<?xml version=”1.0” encoding=”UTF-8”?>
<conversion>
   <from>GBP</from>
   <to>EUR</to>
   <amountToConvert>100</amountToConvert>
   <rate>1.19965499</rate>
   <convertedAmount>119.965499</convertedAmount>
</conversion>

CHAPTER 9 ANSWERS TO EXERCISES

Exercise 1 Solution

You can either list the input numbers (1, 2, 3...) or use (1 to 100) as here:

for $i in (1 to 100)
return $i ∗ $i

Exercise 2 Solution

Here’s one way to do it. You can use normalize-space() because some of the titles in the dictionary have newlines inside them, making the output hard to read.

for $e in //entry[@born and @died]
let $age := xs:integer($e/@died) - xs:integer($e/@born)
where $age gt 88
order by $age descending
return concat(normalize-space($e/title), “ “, $age, “&#xa;”)

Exercise 3 Solution

Please contact the authors directly with the solution image.

Exercise 4 Solution

There is actually only one matching entry, for John Alexander. Find it like this:

for $e in //entry[count(.//p) ge 5]
return concat(normalize-space($e/title),”&#xa;”)

CHAPTER 10 ANSWERS TO EXERCISES

Exercise 1 Solution

The main reasons to choose a relational database with XML features over a pure XML database include the following:

  • Unless all your data is XML, you’ll need a traditional relational database for your tabular data, meaning one that uses two systems.
  • It is easier to have these two forms of data stored in one system rather than two, as it makes writing queries that need elements from both formats simpler.
  • Relational databases are well-established and highly efficient; XML databases are still somewhat rare and understood less.
  • There are few features that XML databases have that can’t be implemented in a relational one but there are many relational features that an XML database just won’t have.

Exercise 2 Solution

The five methods of the xml data type are:

  • query(): Use XQuery or XPath to retrieve and create XML.
  • value(): Use XPath to extract an atomic value as a SQL Server data type.
  • exist(): Check if a particular node exists in an XML document.
  • modify(): Used to replace, delete, or insert nodes in an existing document.
  • nodes(): Used to turn XML into a tabular format so it can be treated a traditional SQL table.

Exercise 3 Solution

There are many candidates to be included in future updates of MySQL’s XML capabilities. Some suggestions include:

  • A proper way to store XML rather than just as text.
  • The ability to return XML fragments defined by XPath rather than just text.
  • Proper namespace handling rather than just having to use the same prefix as defined in the XML.
  • Full XQuery support to be able to create new documents based on ones held in the database.
  • A way to treat XML data as relational similar to SQL Server’s nodes() method.

CHAPTER 11 ANSWERS TO EXERCISES

Exercise 1 Solution

There are four changes to Listing 11-5, SaxParser5.java, which need to be made to receive comment notifications.

1. Add a reference to the org.xml.sax.ext package so that you can use the newer DefaultHandler2 interface. This reference is included with those at the beginning of the file:
      import org.xml.sax.∗;
      import org.xml.sax.helpers.∗;
      import org.xml.sax.ext.∗;
      import java.io.∗;
2. Change the class to inherit from DefaultHandler2:
      public class SaxParser6 extends DefaultHandler2 {
3. Use the setProperty() method to specify the handler that will deal with comments; this needs to be set to the SaxParser6 class itself:
      SaxParser6 parser = new SaxParser6();
      reader.setContentHandler(parser);
      reader.setErrorHandler(parser);
      reader.setProperty(“http://xml.org/sax/properties/lexical-handler”, parser);
4. Add a comment() method to receive the event, this looks very similar to the characters() method:
      public void comment(char[] ch,
             int start,
             int length)
             throws SAXException{
      System.out.print( “SAX Event: COMMENT[ “ );
        StringBuffer commentBuffer = new StringBuffer();
        try {
         commentBuffer.append(ch, start, length);
         System.out.println(commentBuffer.toString()); 
       } catch (Exception e) {
        e.printStackTrace();
       }
      System.out.println(“]”);          
     }

The full code is shown in Listing A-1:

imageLISTING A-1: SaxParser6.java

import org.xml.sax.∗;
import org.xml.sax.helpers.∗;
import org.xml.sax.ext.∗;
import java.io.∗;
 
public class SaxParser6 extends DefaultHandler2 {
 
  private Locator docLocator = null;
  private StringBuffer charactersBuffer = new StringBuffer();
  
  public void setDocumentLocator(Locator locator)
  {
    docLocator = locator;
  }
 
  public void startDocument( ) throws SAXException {
    System.out.println( “SAX Event: START DOCUMENT” );
  }
 
  public void endDocument( ) throws SAXException {
    System.out.println( “SAX Event: END DOCUMENT” );
  }
 
  public void startElement(String namespaceURI,
                           String localName,
                           String qName,
                           Attributes attr ) throws SAXException {
    int lineNumber = 0;
    if (docLocator != null)
    {
      lineNumber = docLocator.getLineNumber();      
    }    
    System.out.println( “SAX Event: START ELEMENT[ “ + localName + “ ]”);
    if (lineNumber != 0)
    {
      System.out.println(“	(Found at line number: “ + lineNumber + “.)”);
    }
    for ( int i = 0; i < attr.getLength(); i++ ){
    System.out.println( “ ATTRIBUTE: “ + attr.getLocalName(i) + 
 “ VALUE: “ + attr.getValue(i) );
    }
    charactersBuffer.setLength(0);
  }
 
  public void endElement(String namespaceURI,
                         String localName,
                         String qName ) throws SAXException {
    System.out.print( “SAX Event: CHARACTERS[ “ );
    System.out.println(charactersBuffer.toString());
    System.out.println( “ ]” );     
    System.out.println( “SAX Event: END ELEMENT[ “ + localName + “ ]” );
  }
 
  public void characters(char[] ch,
                         int start,
                         int length ) throws SAXException {
    try {
      charactersBuffer.append(ch, start, length); 
    } catch (Exception e) {
     e.printStackTrace();
    }
  }
 
  public void warning (SAXParseException exception)
    throws SAXException {
    System.err.println(“[Warning] “ +
      exception.getMessage() + “ at line “ +
      exception.getLineNumber() + “, column “ +
      exception.getColumnNumber() );
  }
 
  public void error (SAXParseException exception)
    throws SAXException {
    System.err.println(“[Error] “ +
      exception.getMessage() + “ at line “ +
      exception.getLineNumber() + “, column “ +
      exception.getColumnNumber() );
  }
 
  public void fatalError (SAXParseException exception)
    throws SAXException {
    System.err.println(“[Fatal Error] “ +
      exception.getMessage() + “ at line “ +
      exception.getLineNumber() + “, column “ +
      exception.getColumnNumber() );
    throw exception;
  }
  
  public void comment(char[] ch,
             int start,
             int length)
             throws SAXException{
   System.out.print( “SAX Event: COMMENT[ “ );
     StringBuffer commentBuffer = new StringBuffer();
     try {
      commentBuffer.append(ch, start, length);
      System.out.println(commentBuffer.toString()); 
    } catch (Exception e) {
     e.printStackTrace();
    }
   System.out.println(“]”);          
  }
  
 
  public static void main( String[] argv ){
    String inputFile = argv[0];
    System.out.println(“Processing '” + inputFile + “'.”);
    System.out.println( “SAX Events:” );
    try {
      XMLReader reader = XMLReaderFactory.createXMLReader();
      SaxParser6 parser = new SaxParser6();
      reader.setContentHandler(parser);
      reader.setErrorHandler(parser);
      reader.setProperty
 (“http://xml.org/sax/properties/lexical-handler”, parser);
      try
      {
        reader.setFeature(“http://xml.org/sax/features/validation”, true);
      } catch (SAXException e) {
      System.err.println(“Cannot activate validation”);
      }
 
      reader.parse( new InputSource(
                 new FileReader( inputFile )));
    }catch ( Exception e ) {
       e.printStackTrace();
    }
  }
}

When this class is run against the PeopleWithComment.xml sample it reports two comments as expected.

Exercise 2 Solution

The way to restrict external file access to be limited to those residing locally, is very similar to the example in “Controlling External Resources” section of the chapter that let files only be retrieved from specific servers. In this case though you use a FileIOPermission rather than a WebPermission as shown in the following snippet:

var localFilesPermission = new FileIOPermission(PermissionState.None);
localFilesPermission.AllLocalFiles = FileIOPermissionAccess.Read;
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(localFilesPermission);
var reader = XmlReader.Create(@”myXmlFile.xml”);
reader.XmlResolver = new XmlSecureResolver(new XmlUrlResolver(), permissionSet);

A FileIOPermision is created and its AllLocalFiles property set to true. This permission is then added to a new PermissionSet which is, in turn, used to construct an XmlSecureResolver.

CHAPTER 12: ANSWERS TO EXERCISES

Answer to Exercise 1

The code is similar to the element-centric version, the only changes being in the CreateMusicLibrary() function:

  Private Function CreateMusicLibrary() As XElement
    Dim cdData = GetCDs()
    Dim musicLibrary =
      <musicLibrary>
        <%= From item In cdData
          Select <cd id=<%= item.ID %> year=<%= item.Year %> artist=<%= item.Artist %> genre=<%= item.Genre %>>
                   <title><%= item.Title %></title>
                 </cd> %>
      </musicLibrary>
    Return musicLibrary
  End Function

The only difference is that the literals used to create the elements, other than that of <title> which remains, have been replaced with those to use attributes.

Module1.vb in AttributeCentricLibrary project

CHAPTER 13 ANSWERS TO EXERCISES

Exercise 1 Solution

You should check the specs and some real-world feeds yourself, but the elements used for identifying the author of an item are usually one of the following: author, dc:creator, atom:name, or foaf:name. The author element appears in the “simple” RSS versions (0.9x, 2.0) and has no namespace. However, note a slight complication: there is also an element in RSS 2.0 called name, which is used for the name of the text object in a text input area (the text input area elements are rarely encountered in practice, but it does make for a more interesting exercise).

The solution will involve adding a little more checking of element names towards the end of the endElementNS method, with code that looks something like this:

...
if localname == “author”:
 
          self.current_item.author = text
          return

Exercise 2 Solution

To determine the format of a feed the obvious approach is to test the root element for its qualified name, with the following possible values:

  • rdf:RDF — RSS 1.0
  • rss — RSS 2.0 (or one of the other “simple” RSS variants)
  • atom:feed — Atom

The title of the feed is in a different part of the document in each case, so here it is:

  • rdf:RDF/rss1:channel/rss1:title — RSS 1.0
  • rss/channel/title — RSS 2.0 (and variants)
  • atom:feed/atom:title — Atom

There are many different ways of examining/accessing the parts of an XML document with XSLT. Here is a sample solution that demonstrates two approaches:

<xsl:stylesheet version=”1.0”  
    xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
    xmlns:xhtml=”http://www.w3.org/1999/xhtml”
    xmlns:atom=”http://www.w3.org/2005/Atom”
    xmlns:rss1=”http://purl.org/rss/1.0/”
    xmlns:rdf=”http://www.w3.org/1999/02/22-rdf-syntax-ns#”
    xmlns:dc=”http://purl.org/dc/elements/1.1/”>
 
<xsl:output method=”html” indent=”yes”/>  
 
<xsl:template match=”/”>
  <xsl:text disable-output-escaping=”yes”>
    &lt;!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” 
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
  </xsl:text>
  <html>
  <head>
    <title>Feed Info</title>
  </head>
  <body>
<dl>
  <dt>Format : </dt>
    <dd> 
<xsl:if test=”/rdf:RDF”>RSS 1.0</xsl:if>
<xsl:if test=”/rss”>RSS 2.0</xsl:if>
<xsl:if test=”/atom:feed”>Atom</xsl:if>
</dd>
  <dt>Title : </dt>
    <dd><xsl:apply-templates /></dd>
</dl> 
 
  </body>
  </html>
</xsl:template>
 
<xsl:template match=”rdf:RDF”>
    <xsl:value-of select=”rss1:channel/rss1:title” />
</xsl:template>
   
<xsl:template match=”rss”>
    <xsl:value-of select=”channel/title” />
</xsl:template>
 
<xsl:template match=”atom:feed”>
    <xsl:value-of select=”atom:title” />
</xsl:template>
 
<xsl:template match=”text()” />
 
</xsl:stylesheet>
 

Checking the root element to detect the format (and supplying a suitable display value) is achieved through a series of simple xsl:if expressions, e.g:

<xsl:if test=”/rdf:RDF”>RSS 1.0</xsl:if>

So here if the root element of the document has the name RDF and is in the appropriate namespace (declared as http://www.w3.org/1999/02/22-rdf-syntax-ns#), the value “RSS 1.0” will be passed to the output from the XSLT.

The titles are extracted using templates, for example:

<xsl:template match=”atom:feed”>
    <xsl:value-of select=”atom:title” />
</xsl:template>

Here, if there’s a match in the document to Atom’s root element, this template will pull out the text content of the corresponding title element for the feed.

CHAPTER 14 ANSWERS TO EXERCISES

Exercise 1 Solution

There are three pieces of information to send so you have two choices: either send three parameters or wrap the three pieces of data in a structure and send the structure. The first of these options would look like the following:

<methodCall>
  <methodName>AdSevice.Add</methodName>
  <params>
    <param>
      <value>
        <string>Joe Fawcett</string>
      </value>
    </param>
    <param>
      <value>
        <string>555-1234</string>
      </value>
    </param>
    <param>
      <value>
        <string><![CDATA[ My dog, Fido, has gone missing
 from my home near... ]]></string>
      </value>
    </param>
  </params>
</methodCall>

The second option, using a structure would look like the following:

<methodCall>
  <methodName>AdService.Add</methodName>
  <params>
    <param>
      <value>
        <struct>
          <member>
            <name>Name</name>
            <value>
              <string>Joe Fawcett</string>
            </value>
          </member>
          <member>
            <name>PhoneNumber</name>
            <value>
              <string>555-1234</string>
            </value>
          </member>
          <member>
            <name>AdText</name>
            <value>
              <string><![CDATA[ My dog, Fido, has gone missing
 from my home near... ]]></string>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodCall>

Exercise 2 Solution

In theory REST style requests don’t have to have any bearing on what they are trying to achieve but in practice most people like to make them guessable, that is if you have seen one you can guess the format needed for similar ones. In addition to the request having an easy to understand format, most REST services shy away from using the querystring to pass data and prefer instead to use the different components of the URL. Bearing these two practices in mind, a typical request would look like one of the following:

http://services.wrox.com/customer/3263827/order/THX1138

http://services.wrox.com/orderinquiry/3263828/THX1138

CHAPTER 15 ANSWERS TO EXERCISES

Exercise 1 Solution

The SOAP document will look similar to the following:

image <soap:Envelope
  xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”
  soap:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”>
  <soap:Body>
    <q:StockPriceRequest xmlns:q=”http://wrox.com/beginningXml/stockprice”>
      <StockSymbol>MSFT</StockSymbol>
    </q:StockPriceRequest>
  </soap:Body>
</soap:Envelope>

StockPriceRequest.xml

Your answer may differ in the choice of namespace bound to the q prefix and, of course, you may have chosen a different prefix altogether.

Exercise 2 Solution

There can be quite a variety in how the WSDL looks but a sample is shown here:

image <?xml version=”1.0”?>
<definitions name=”StockPrice”
             targetNamespace=
“http://wrox.com/beginningXml/stockprice”
             xmlns:tns=”http://wrox.com/beginningXml/stockprice”
             xmlns:q=”http://wrox.com/beginningXml/stockprice/”
             xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/”
             xmlns=”http://schemas.xmlsoap.org/wsdl/”>
 
  <types>
    <schema targetNamespace=”http://wrox.com/beginningXml/stockprice”
            xmlns=”http://www.w3.org/2000/10/XMLSchema”>
      <element name=”StockPriceRequest”>
        <complexType>
          <all>
            <element name=”StockSymbol” type=”string”/>
          </all>
        </complexType>
      </element>
      <element name=”StockPriceResponse”>
         <complexType>
           <all>
             <element name=”price” type=”decimal”/>
           </all>
         </complexType>
      </element>
    </schema>
  </types>
 
  <message name=”GetStockPriceRequest”>
    <part name=”body” element=”q:StockPriceRequest”/>
  </message>
 
  <message name=”GetStockPriceResponse”>
    <part name=”body” element=”q:StockPriceResponse”/>
  </message>
 
  <portType name=”StockPricePortType”>
    <operation name=”GetStockPrice”>
      <input message=”tns:GetStockPriceRequest”/>
      <output message=”tns:GetStockPriceResponse”/>
    </operation>
  </portType>
 
  <binding name=”StockPriceSoapBinding” 
 type=”tns:StockPricePortType”>
    <soap:binding style=”document”
 transport=”http://schemas.xmlsoap.org/soap/http”/>
    <operation name=”GetStockPrice”>
      <soap:operation soapAction=
 “http://wrox.com/beginningXml/GetStockPrice”/>
      <input>
        <soap:body use=”literal”/>
      </input>
      <output>
        <soap:body use=”literal”/>
      </output>
    </operation>
  </binding>
 
  <service name=”StockPriceService”>
    <documentation>Example stock price service</documentation>
    <port name=”StockPricePort”
 binding=”tns:StockPriceSoapBinding”>
      <soap:address
 location=”http://wrox.com/beginningXml/services/stock”/>
    </port>
  </service>
 
</definitions>

StockPrice.wsdl

The main point is that the namespace chosen in Exercise 1 is the same as the targetNamespace attribute on the <schema> element and that the element name specified in the <message> section and the names specified by <element> elements in the <schema> section also match.

CHAPTER 16 ANSWERS TO EXERCISES

Exercise 1 Solution

You could add a second loop, perhaps like this:

# match on start of an interior word
$wordstart = ' ' . $q;
foreach ($items as $key => $value) {
    $where = strpos(strtolower($value), $wordstart);
    if ($where !== false) {
        echo “$value
”;
        if (++$n_found > $maxitems) {
            return;
        }
    }
}

Exercise 2 Solution

Here’s one way to do it. The regular expression handling in PHP is less central than in Perl, but is still very useful. You could use strpos() again instead, though, if you were careful not to match strings already returned.

# next, anywhere in the word ∗except∗ at the start
# of a word
$pattern = '/[^ #]$q.∗#/i';
foreach ($items as $key => $value) {
    $where = preg_match($pattern, $value);
    if ($where !== false && $where != 0) {
        echo “$value
”;
        if (++$n_found > $maxitems) {
            echo “
”;
            return;
        }
    }
}

Exercise 3 Solution

This question could be a project for an undergraduate class, or could be done in a day or two by someone fairly determined. The result is a very powerful architecture that is explored a little more in Chapter 19, “Case Study: XML in Publishing.”

CHAPTER 17 ANSWERS TO EXERCISES

Exercise 1 Solution

Change the margin-left property of the p rule to be at least 150px, and change the margin-left of the img rule from −73 pixels to 150 pixels or more.

Exercise 2 Solution

HML was defined as an SGML application; the SGML is ISO 8879, the Standard Generalized Markup Language.

Exercise 3 Solution

CSS margins are outside the border, and padding is inside the border, between the border and the content. CSS top and bottom margins collapse when blocks are adjacent; padding never collapses. CSS margins are always transparent, whereas padding takes on the element’s background.

Exercise 4 Solution

The HTML 5 specification defines the algorithm to be used to parse the input regardless of whether it conforms. All browsers use the same algorithm.

CHAPTER 18 ANSWERS TO EXERCISES

Exercise 1 Solution

A <circle> element has a single radius attribute, r; an <ellipse> element has two, rx and ry.

Exercise 2 Solution

Any two of SMIL animations, scripted animations, CSS animations, or using a library (which will in turn probably use one or more of the other three methods).

Exercise 3 Solution

It is important to provide text descriptions so that a web search engine crawler can index the text, making the diagram findable using a web search. It is also important to make web pages accessible to people who are blind, and the <desc> element enables those people to understand the diagram or picture based on textual descriptions of the various components.

Exercise 4 Solution

In the lowercase versions of the commands, the coordinates are relative to the starting point of the subpath, and in the uppercase version they are absolute.

CHAPTER 19 ANSWERS TO EXERCISES

Exercise 1 Solution

The XSD namespace was used in the style sheet; the XSLT processor has no way of knowing it’s not needed, because you might be using QNames in content, for example <type>xs:integer</type>. To remove it, along with the XSLT namespace, add the following to the <xsl:stylesheet> element’s start tag:

exclude-result-prefixes=”xs xsl”

Exercise 2 Solution

Use something like this:

<xlink:a href=”{@id}.html”><xsl:apply-templates/></xlink:a>

You’ll have to declare the xlink namespace prefix properly of course; see Chapter 18 for examples.

Exercise 3 Solution

The team at Hoy Books used XQuery to extract information from inside documents. With a relational database they would have needed to extract the information on import (perhaps using a Visual Basic program) and store it in separate tables, risking integrity problems. They would also have had a greater mixture of technologies with their respective limitations and necessary skills, because they need to generate XHTML for e-book publishing. Perhaps you can come up with other advantages.

Exercise 4 Solution

[open-ended]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.123.73