Home > Articles > Web Services > XML

  • Print
  • + Share This
This chapter is from the book

Essential XML

The engine that drives the Web Service is the Simple Object Access Protocol, or SOAP. SOAP's power is centered on the intrinsic behavior of XML and related XML technologies. To fully appreciate SOAP and its capabilities, it's important to have a good understanding of XML. It is beyond the scope of this book to teach you all you might need to know to use XML effectively. However, it would be unreasonable to assume that you understand all the emerging technologies associated with XML because several of these are still ongoing efforts. Therefore, this section briefly reviews XML to provide the basis for discussion of the newer aspects to XML.

Documents, Elements, and Attributes

An XML document is really just a collection of data consisting of both physical and logical structure. Physically, the document consists of textual information. It contains entities that can reference other entities that are located elsewhere in memory, on a hard disk, or, more importantly, on the Web. The logical structure of an XML document includes processing instructions, declarations, comments, and elements. XML documents contain ordinary text (as specified by ISO/IEC 10646) that represent markup or character data.

The general form of an XML document looks something like this:

<?xml version="1.0" ?>
<Car Year="2002">
   <Make>Chevrolet</Make>
   <Model>Corvette<Model>
   <Color>Gunmetal</Color>
</Car>

You know that this is an XML document because of the XML declaration on the first line that tells you that this document conforms to XML version 1.0. In this example, <Car/> is the root element or document element of this XML document, <Make/> is just one of the child elements contained within <Car/>, and Year is an attribute of the <Car/> element.

Any text document is considered a well-formed XML document if it conforms to the constraints set forth in the XML specification. For example, one very important constraint is the limitation to one and only one root element in a document. An XML document is considered valid if it is well formed, if it has an associated Document Type Definition (DTD) or XML Schema, and if the given instance document complies with this definition. The DTD or XML Schema documents act as a template that the associated XML document must precisely match. If not, there is a problem with the formatting of the instance document, and the entire document is considered not valid.

It is common to find processing instructions embedded within the document, but they are not considered part of the document's content. They are used to communicate information to application-level code without changing the meaning of the XML document's content.

The following notation denotes the syntax of processing instructions:

<?target declaration ?>

The processing instruction contains a target followed by one or more instructions, where the target name specifies the application to which the processing instruction is applied. A common target name found in XML documents is the reserved target xml. This enables the XML document to communicate instructions to XML parsers. The most common (but optional) processing instruction used in XML documents is the XML declaration itself.

Recall that an element consists of a start tag, an end tag, and a value. But what if you have no value? Do you omit the entire XML element? You could, but it's also useful information to know that an element could be there but, in this particular case, you have no value. Rather than using a start and end tag when you have no value to include, you can combine the tags to form an empty-element tag:

<Car Year="2002">
   <Make>Chevrolet</Make>
   <Model>Corvette<Model>
   <Color>Gunmetal</Color>
   <VehicleID/>
</Car>

NOTE

XML is sensitive to case and whitespace when creating element names. Whitespace is never legal in tag names, and tag names that are spelled the same but differ in alphabetical case represent different XML elements.

A parent element can theoretically contain an infinite number of child elements, and the same child element can appear multiple times under its parent element as siblings:

<Car>
    <Name>Corvette</Name>
    <Name>Speedy<Name>
    <Color>Red</Color>
    <!-- ...etc... -->
</Car>

Also, the same element name can appear under different parent elements. In this case, the element <Name appears under the <Car> element as well as the <SoundSystem> element:

<Car>
    <Name>Corvette</Name>
    <SoundSystem>
        <Name>Bose</Name>
   </SoundSystem>
</Car>

You are not allowed to overlap tags within an XML document. The following document would not be considered a well-formed XML document because the <Color> element starts before the <Name> element ends:

<Car>
   <Color>3721-<Name>Red</Color>Corvette</Name>
</Car>

This example is trying to specify that the color of the car is 3721-Red and the name of the car is RedCorvette. However, this does not meet the XML specification constraints. Instead, it should be rewritten as follows:

<Car>
    <Color>3721-Red</Color><Name>RedCorvette</Name>
</Car>
Elements can be embedded within values of other elements:
<Car>
    <Name>Corvette</Name>
    <Base>MSRP<Price>39,475</Price>with options</Base>
</Car>

In this case, the <Price> element was embedded between the first part of the MSRP value and the last part of the with options value. This XML document encoding style is very much discouraged in general practice, however. The most common way to logically view an XML document is as a tree, and having elements embedded within values muddies this model.

Attributes provide more specific information about a particular element. Choosing between using an attribute and using an element can sometimes be a difficult decision. In a lot of cases, either form will work. One approach is to use attributes to denote element classifications based on the problem domain. Or, consider the attribute as a way to insert metadata that tailors the element in some way. Another aspect to using attributes deals with ease of access to data. If you always want to obtain the car's color every time you encounter a Car element, then Color might be a good candidate for an attribute.

NOTE

The SOAP specification uses attributes in a variety of ways. In particular, the id and href attributes are used for unique identifiers and references, respectively. They are part of XLink, which you'll see in the section "Identifying XML Elements Using XLink."

Entity References and CDATA

It is not uncommon for character data to contain characters that are used in XML constructs. The following XML does not conform to the XML specification:

<Car Year="2002 "The Sleekest Vette Yet"">
    <Name>Corvette</Name>
</Car>

The additional quotes in "The Sleekest Vette Yet" corrupt the syntax of the root element. Proper use of entity references allows you to instruct parsers to treat data as character data. The preceding example should be changed to this:

<Car Year="2000 &quot;The New Millennium&quot;">
    <Name>Corvette</Name>
</Car>

Here, the quotes have been replaced by their entity reference and will now be correctly parsed.

The double quote is but one of five characters that must be replaced with their entity references. The other four include the apostrophe (single quote), the ampersand, and the "less than" and "greater than" brackets. This makes sense because the quote characters are used to encapsulate attributes, the ampersand denotes an entity reference, and the brackets form XML element tags. If you use these characters within general text element values, you confuse the XML parser.

CDATA is an alternate form of markup that is better for larger quantities of text to be explicitly described as character data:

<Car Year="2002">
    <Model>Corvette</Model>
    <Description><![CDATA["I bet it's fast!"]]></Description>
</Car>

Rather than using entity references for each individual character, you can specify that an entire block of text should be treated as character data. This is a nice benefit because you do not need to replace each special character with its entity reference, which can be costly in terms of string manipulations. You simply wrap the text data with the CDATA tag.

There are two limitations to CDATA, however. CDATA sections cannot be nested within one another, and you cannot use CDATA within attribute values. CDATA sections cannot be nested because, by XML specification, the end tag of the enclosing CDATA section is considered to be the end tag for the CDATA section. If there were more text after this tag, the XML parser would become confused and would return to you an error when the document was parsed. For attributes, it is not legal XML syntax to specify XML elements within attribute values, and CDATA falls within that ruling. If you happen to have textual data that contains some of the XML special characters, you should use their respective entity reference values instead.

URIs and XML Namespaces

URI, or uniform resource identifier, is a generic term used to identify some particular entity or object in the Web world using its string representation. This is the most fundamental addressing scheme of the Web. A perfect use for this uniqueness deals with naming XML elements and attributes so that they don't conflict with one another. This section reviews the characteristics of URIs and namespaces, and describes how they are related when used with your XML documents.

URLs and URNs

Different types of Web resources require different forms of URIs. Specifically, uniform resource locators (URLs) and uniform resource names (URNs) are both forms of a URI (see Figure 3.1). Each has its own syntax designed to fulfill a purpose.

Figure 3.1 The relationship between URIs, URNs, and URLs.

URLs are a form of URI used to locate a particular resource in the Web world. Basic URL syntax (see RFC 1738) is dependent on the scheme to which it applies, but it follows this format:

<scheme>:<scheme-specific syntax>

One form of a URL is used to specify a Web page located on a Web server, similar to this:

http://www.endurasoft.com/educenter.htm

In this case, the scheme indicates that the HTTP protocol is to be used to retrieve the HTML text for a particular Web page. By changing just one of the values in this URL, you are specifying a completely different location, resource, or both on the Web.

URNs are another form of URI that provides persistence as well as location-independence. In a nutshell, a URN uniquely describes some resource that will always be available. The following is an example of a URN:

urn:foo-bar:foobar.1

The exact syntax of URNs is denoted in RFC 2141, but the following is a summary:

urn:<Namespace Identifier>:<Namespace Specific String>

  1. The text "urn:" (uppercase or lowercase) is included.

  2. The Namespace Identifier consists of letters, numbers, and hyphens (uppercase or lowercase).

  3. The Namespace Specific String consists of letters, numbers, parentheses, commas, periods, hyphens, and other such characters (uppercase or lowercase).

Efforts are underway to provide Internet protocols for resolving URNs. This would work similar to the way DNS (or other name service) resolves hostnames.

XML Namespaces

In the .NET Framework, namespaces are used routinely to uniquely identify groupings of logically related classes that might have names that coincide with classes within other framework class groupings. XML also uses namespaces, but for a slightly different purpose. Because you are free to create your own XML elements, chances are good that you will happen to select a tag name that someone else has also used. With everyone declaring their own XML element names and attributes, you can expect ambiguous results when trying to combine this data. For example, one system might use the <Title/> element when describing a book, while another system might also use <Title/> to describe automobile ownership. As long as the XML data from the two systems is never combined within the same XML document, everything is fine. However, if the data ever merges, there is no way to distinguish between the two semantic meanings.

An XML namespace, as identified by a URI reference, qualifies element and attribute names within an XML document. This not only avoids name collisions, but it also enables vocabularies to be reused. You can think of an XML vocabulary as a published set of element and attribute names common to a particular user domain. SOAP is one such vocabulary, but there are many others.

The following example contains XML that has no associated namespace:

<Product>
    <ProductName Type="1">Widget</ProductName>
</Product>

To reference a namespace, you must first declare one by creating a namespace declaration using this form:

xmlns:<Namespace Prefix> = <URI>

In the namespace declaration, you specify a namespace prefix and the URI of the namespace. The prefix is attached to the local names of elements and attributes so that they are associated with the correct namespace, like so:

<pns:Product xmlns:pns="http://www.endurasoft.com/prodns">
    <pns:ProductName pns:Type="1">Widget</pns:ProductName>
</pns:Product>

In this case, pns is defined to be the prefix and is used to associate Product, ProductName, and Type with the http://www.endurasoft.com/prodns URI. In reality, the URI doesn't necessarily point to anything—its purpose is to provide uniqueness to the namespace.

XML namespaces also provide the concept of a default namespace (denoted in XML as xmlns). This enables you to establish a namespace for an element and all its children, thus avoiding the need to use a prefix on each element name.

NOTE

Default namespaces do not apply to attribute names. Instead, attributes must be explicitly prefixed to the desired namespace.

Initially, an XML document has no assigned default namespace, so any elements that are not qualified with a prefix will be locally scoped.

Now consider the following example:

<pns:Product xmlns:pns="http://www.endurasoft.com/prodns">
    <pns:ProductName pns:Type="1">Widget</pns:ProductName>
    <ProductLoc xmlns="http://www.endurasoft.com/prodlocns">
        <Building>310</Building>
        <Floor>2</Floor>
        <Room>118</Room>
    </ProductLoc>
    <Cost>495.00</Cost>
</pns:Product>

On the first line, the pns prefix is created to reference a product URI. This same prefix is used to qualify the Product and ProductName elements. On the third line, a default namespace is created that references a completely different URI than did the first line. All elements contained within the ProductLoc element are scoped to the default namespace and, therefore, require no prefix. However, because <Cost/> element is not contained by the ProductLoc element and doesn't have a prefix, it is considered locally scoped to the document.

.NET uses namespaces. If you examine the XML used to transfer information between the Web Service and the client, you'd see these namespaces in action. They're simply there to identify a certain XML element as belonging to a logically related group of XML elements that form a vocabulary. But how is the vocabulary itself specified? This is the primary use of the XML Schema.

  • + Share This
  • 🔖 Save To Your Account