XML za apsolutnog početnika

HTML i World Wide Web su svugdje. Kao primjer njihove sveprisutnosti, ove godine idem u Srednju Ameriku za Uskrs, a ako želim, moći ću surfati webom, čitati e-poštu i čak obavljati internetsko bankarstvo iz internetskih kafića u Antigva Gvatemala i grad Belize. (Međutim, ne namjeravam jer bi mi to oduzelo vrijeme od datuma kojeg imam s palmom i kokosom punjenim rumom.)

Pa ipak, unatoč sveprisutnosti i popularnosti HTML-a, jako je ograničen u onome što može učiniti. To je u redu za širenje neformalnih dokumenata, ali HTML se sada koristi za radnje za koje nikada nije dizajniran. Pokušaj dizajniranja teških, fleksibilnih, interoperabilnih podatkovnih sustava iz HTML-a je poput pokušaja izrade nosača zrakoplova s ​​pilama i lemilicama: alati (HTML i HTTP) jednostavno nisu dorasli poslu.

Dobra vijest je da su mnoga ograničenja HTML-a prevladana u XML-u, proširivom označnom jeziku. XML je lako razumljiv svima koji razumiju HTML, ali je puno snažniji. XML je više od samog jezika za označavanje metajezik - jezik koji se koristi za definiranje novih označnih jezika. Pomoću XML-a možete stvoriti jezik izrađen posebno za vašu aplikaciju ili domenu.

XML će nadopuniti, umjesto zamijeniti, HTML. Dok se HTML koristi za oblikovanje i prikaz podataka, XML predstavlja kontekstualno značenje podataka.

Ovaj će članak predstaviti povijest označnih jezika i kako je nastao XML. Pogledat ćemo uzorke podataka u HTML-u i postupno prijeći u XML, pokazujući zašto pružaju vrhunski način predstavljanja podataka. Istražit ćemo razloge zbog kojih biste mogli izumiti prilagođeni jezik za označavanje i naučit ću vas kako to učiniti. Obuhvatit ćemo osnove XML zapisa i kako prikazati XML s dvije različite vrste stilskih jezika. Zatim ćemo zaroniti u Document Object Model, moćan alat za manipulaciju dokumentima kao objektima (ili manipuliranjem objektnim strukturama kao dokumentima, ovisno o tome kako ga gledate). Ići ćemo kako napisati Java programe koji izvlače informacije iz XML dokumenata, s pokazivačem na besplatni program koristan za eksperimentiranje s tim novim konceptima. Napokon,Pogledat ću internetsku tvrtku koja svoju temeljnu tehnološku strategiju temelji na XML-u i Javi.

Je li XML za vas?

Iako je ovaj članak napisan za sve koje zanima XML, on ima poseban odnos prema seriji JavaWorld na XML JavaBeans. (Pogledajte Resurse za poveznice na srodne članke.) Ako ste čitali tu seriju i ne razumijete je, ovaj bi članak trebao pojasniti kako koristiti XML s grahom. Ako se to tiče, ovaj članak služi kao savršen pratitelj komada u seriji XML JavaBeans, jer pokriva teme netaknuta u njemu. A ako ste jedan od rijetkih sretnika koji se još uvijek raduju XML JavaBeans člancima, preporučujem da ovaj članak pročitate prvo kao uvodni materijal.

Bilješka o Javi

U računalnom svijetu postoji toliko nedavnih XML aktivnosti da čak i članak ove duljine može samo preletjeti površinu. Ipak, cijela poanta ovog članka je dati vam kontekst potreban za upotrebu XML-a u dizajnu Java programa. Ovaj članak također pokriva kako XML radi s postojećom web tehnologijom, jer mnogi programeri Java rade u takvom okruženju.

XML otvara programiranje Interneta i Jave za prijenosnu funkcionalnost bez pregledavanja. XML oslobađa internetski sadržaj iz preglednika na sličan način kao što Java oslobađa ponašanje programa s platforme. XML čini internetski sadržaj dostupnim stvarnim aplikacijama.

Java je izvrsna platforma za korištenje XML-a, a XML je izvanredan prikaz podataka za Java programe. Upozorit ću na neke jake prednosti Jave s XML-om tijekom razvoja.

Počnimo s poukom povijesti.

Podrijetlo označnih jezika

HTML koji svi znamo i volimo (dobro, ionako znamo) izvorno je dizajnirao Tim Berners-Lee iz CERN-a ( Conseil Européen pour la Recherche Nucléaire, ili Europski laboratorij za fiziku čestica) u Ženevi kako bi fizičkim štreberima omogućio ( pa čak i ne-štreberi) da međusobno komuniciraju. HTML je objavljen u prosincu 1990. u okviru CERN-a, a svima nama postao je dostupan u ljeto 1991. godine. CERN i Berners-Lee dali su specifikacije za HTML, HTTP i URL-ove, u lijepoj staroj tradiciji Interneta dijelite i uživajte.

Berners-Lee definirao je HTML u SGML-u, standardnom generaliziranom jeziku za označavanje. SGML je, poput XML, metajezik - jezik koji se koristi za definiranje drugih jezika. Svaki tako definirani jezik naziva se aplikacijom SGML-a. HTML je aplikacija SGML-a.

SGML je proizašao iz istraživanja provedenog prvenstveno u IBM-u na predstavljanju tekstualnih dokumenata krajem 60-ih. IBM je stvorio GML ("General Markup Language"), jezik prethodnik SGML-a, a 1978. Američki nacionalni institut za standarde (ANSI) stvorio je svoju prvu verziju SGML-a. Prvi je standard objavljen 1983., a nacrt standarda objavljen 1985., a prvi je standard objavljen 1986. Zanimljivo je da je prvi SGML standard objavljen pomoću SGML sustava koji je razvio Anders Berglund iz CERN-a, organizacije koja je kao vidjeli smo, dali su nam HTML i Web.

SGML se široko koristi u velikim industrijama i vladama, poput velikih zrakoplovnih, automobilskih i telekomunikacijskih tvrtki. SGML se koristi kao standard dokumenata u Ministarstvu obrane Sjedinjenih Američkih Država i Poreznoj upravi. (Za čitatelje izvan SAD-a porezna uprava je porezna služba.)

Albert Einstein rekao je da sve treba učiniti što jednostavnijim, a ne jednostavnijim. Razlog zašto se SGML ne može naći na više mjesta jest taj što je izuzetno sofisticiran i složen. A HTML, koji možete pronaći svugdje, vrlo je jednostavan; za puno aplikacija je previše jednostavno.

HTML: Sav oblik i bez supstanci

HTML je jezik dizajniran da "govori o" dokumentima: zaglavljima, naslovima, natpisima, fontovima itd. Orijentiran je u velikoj mjeri na strukturu i prezentaciju dokumenata.

Doduše, umjetnici i hakeri mogli su raditi čuda s relativno dosadnim alatom zvanim HTML. Ali HTML ima ozbiljnih nedostataka koji ga čine lošim za dizajniranje fleksibilnih, moćnih, evolucijskih informacijskih sustava. Evo nekoliko glavnih prigovora:

  • HTML se ne može proširiti

    Proširivi označni jezik omogućio bi programerima aplikacija da definiraju prilagođene oznake za situacije specifične za aplikaciju. Ako niste gorila od 600 kilograma (a možda ni tada), ne možete zahtijevati od svih proizvođača preglednika da implementiraju sve oznake oznake potrebne za vašu aplikaciju. Dakle, zapeli ste s onim što će vam omogućiti veliki proizvođači preglednika ili W3C (World Wide Web Consortium). Ono što nam treba je jezik koji nam omogućuje da sami izrađujemo oznake za označavanje bez potrebe da zovemo proizvođača preglednika.

  • HTML je vrlo usmjeren na prikaz

    HTML is a fine language for display purposes, unless you require a lot of precise formatting or transformation control (in which case it stinks). HTML represents a mixture of document logical structure (titles, paragraphs, and such) with presentation tags (bold, image alignment, and so on). Since almost all of the HTML tags have to do with how to display information in a browser, HTML is useless for other common network applications -- like data replication or application services. We need a way to unify these common functions with display, so the same server used to browse data can also, for example, perform enterprise business functions and interoperate with legacy systems.

  • HTML isn't usually directly reusable

    Creating documents in word-processors and then exporting them as HTML is somewhat automated but still requires, at the very least, some tweaking of the output in order to achieve acceptable results. If the data from which the document was produced change, the entire HTML translation needs to be redone. Web sites that show the current weather around the globe, around the clock, usually handle this automatic reformatting very well. The content and the presentation style of the document are separated, because the system designers understand that their content (the temperatures, forecasts, and so on) changes constantly. What we need is a way to specify data presentation in terms of structure, so that when data are updated, the formatting can be "reapplied" consistently and easily.

  • HTML only provides one 'view' of data

    It's difficult to write HTML that displays the same data in different ways based on user requests. Dynamic HTML is a start, but it requires an enormous amount of scripting and isn't a general solution to this problem. (Dynamic HTML is discussed in more detail below.) What we need is a way to get all the information we may want to browse at once, and look at it in various ways on the client.

  • HTML has little or no semantic structure

    Most Web applications would benefit from an ability to represent data by meaning rather than by layout. For example, it can be very difficult to find what you're looking for on the Internet, because there's no indication of the meaning of the data in HTML files (aside from META tags, which are usually misleading). Type

    red

    into a search engine, and you'll get links to Red Skelton, red herring, red snapper, the red scare, Red Letter Day, and probably a page or two of "Books I've Red." HTML has no way to specify what a particular page item means. A more useful markup language would represent information in terms of its meaning. What we need is a language that tells us not how to

    display

    information, but rather, what a given block of information

    is

    so we know what to do with it.

SGML has none of these weaknesses, but in order to be general, it's hair-tearingly complex (at least in its complete form). The language used to format SGML (its "style language"), called DSSSL (Document Style Semantics and Specification Language), is extremely powerful but difficult to use. How do we get a language that's roughly as easy to use as HTML but has most of the power of SGML?

Origins of XML

As the Web exploded in popularity and people all over the world began learning about HTML, they fairly quickly started running into the limitations outlined above. Heavy-metal SGML wonks, who had been working with SGML for years in relative obscurity, suddenly found that everyday people had some understanding of the concept of markup (that is, HTML). SGML experts began to consider the possibility of using SGML on the Web directly, instead of using just one application of it (again, HTML). At the same time, they knew that SGML, while powerful, was simply too complex for most people to use.

In the summer of 1996, Jon Bosak (currently online information technology architect at Sun Microsystems) convinced the W3C to let him form a committee on using SGML on the Web. He created a high-powered team of muckety-mucks from the SGML world. By November of that year, these folks had created the beginnings of a simplified form of SGML that incorporated tried-and-true features of SGML but with reduced complexity. This was, and is, XML.

In March 1997, Bosak released his landmark paper, "XML, Java and the Future of the Web" (see Resources). Now, two years later (a very long time in the life of the Web), Bosak's short paper is still a good, if dated, introduction to why using XML is such an excellent idea.

SGML was created for general document structuring, and HTML was created as an application of SGML for Web documents. XML is a simplification of SGML for general Web use.

An XML conceptual example

All this talk of "inventing your own tags" is pretty foggy: What kind of tags would a developer want to invent and how would the resulting XML be used? In this section, we'll go over an example that compares and contrasts information representation in HTML and XML. In a later section ("XSL: I like your style") we'll go over XML display.

First, we'll take an example of a recipe, and display it as one possible HTML document. Then, we'll redo the example in XML and discuss what that buys us.

HTML example

Take a look at the little chunk of HTML in Listing 1:

   Lime Jello Marshmallow Cottage Cheese Surprise   

Lime Jello Marshmallow Cottage Cheese Surprise

My grandma's favorite (may she rest in peace).

Ingredients

Qty Units Item
1 box lime gelatin
500 g multicolored tiny marshmallows
500 ml cottage cheese
dash Tabasco sauce (optional)

Instructions

  1. Prepare lime gelatin according to package instructions...

Listing 1. Some HTML

(A printable version of this listing can be found at example.html.)

Looking at the HTML code in Listing 1, it's probably clear to just about anyone that this is a recipe for something (something awful, but a recipe nonetheless). In a browser, our HTML produces something like this:

Lime Jello Marshmallow Cottage Cheese Surprise

My grandma's favorite (may she rest in peace).

Ingredients

Qty Units Item
1 box lime gelatin
500 g multicolored tiny marshmallows
500 ml Cottage cheese
  dash Tabasco sauce (optional)

Instructions

  1. Prepare lime gelatin according to package instructions...

Listing 2. What the HTML in Listing 1 looks like in a browser

Now, there are a number of advantages to representing this recipe in HTML, as follows:

  • It's fairly readable. The markup may be a little cryptic, but if it's laid out properly it's pretty easy to follow.

  • The HTML can be displayed by just about any HTML browser, even one without graphics capability. That's an important point: The display is browser-independent. If there were a photo of the results of making this recipe (and one certainly hopes there isn't), it would show up in a graphical browser but not in a text browser.

  • You could use a cascading style sheet (CSS -- we'll talk a bit about those below) for general control over formatting.

There's one major problem with HTML as a data format, however. The meaning of the various pieces of data in the document is lost. It's really hard to take general HTML and figure out what the data in the HTML mean. The fact that there's an of this recipe with a (quantity) of 500 ml () of cottage cheese would be very hard to extract from this document in a way that's generally meaningful.

Now, the idea of data in an HTML document meaning something may be a bit hard to grasp. Web pages are fine for the human reader, but if a program is going to process a document, it requires unambiguous definitions of what the tags mean. For instance, the tag in an HTML document encloses the title of the document. That's what the tag means, and it doesn't mean anything else. Similarly, an HTML tag means "table row," but that's of little use if your program is trying to read recipes in order to, say, create a shopping list. How could a program find a list of ingredients from a Web page formatted in HTML?

Sure, you could write a program that grabs the headers out of the document, reads the table column headers, figures out the quantities and units of each ingredient, and so on. The problem is, everyone formats recipes differently. What if you're trying to get this information from, say, the Julia Childs Web site, and she keeps messing around with the formatting? If Julia changes the order of the columns or stops using tables, she'll break your program! (Though it has to be said: If Julia starts publishing recipes like this, she may want to think about changing careers.)

Now, imagine that this recipe page came from data in a database and you'd like to be able to ship this data around. Maybe you'd like to add it to your huge recipe database at home, where you can search and use it however you like. Unfortunately, your input is HTML, so you'll need a program that can read this HTML, figure out what all the "Ingredients," "Instructions," "Units," and so forth are, and then import them to your database. That's a lot of work. Especially since all of that semantic information -- again, the meaning of the data -- existed in that original database but were obscured in the process of being transformed into HTML.

Now, imagine you could invent your own custom language for describing recipes. Instead of describing how the recipe was to be displayed, you'd describe the information structure in the recipe: how each piece of information would relate to the other pieces.

XML example

Let's just make up a markup language for describing recipes, and rewrite our recipe in that language, as in Listing 3.

  Lime Jello Marshmallow Cottage Cheese Surprise  My grandma's favorite (may she rest in peace).    1 lime gelatin   500 multicolored tiny marshmallows   500 Cottage cheese    Tabasco sauce     Prepare lime gelatin according to package instructions     

Listing 3. A custom markup language for recipes

It will come as little surprise to you, being the astute reader you are, that this recipe in its new format is actually an XML document. Maybe the fact that the file started with the odd header


  

gave it away; in fact, every XML file should begin with this header. We've simply invented markup tags that have a particular meaning; for example, "An is a (quantity in specified units) of a single , which is possibly optional." Our XML document describes the information in the recipe in terms of recipes, instead of in terms of how to display the recipe (as in HTML). The semantics, or meaning of the information, is maintained in XML because that's what the tag set was designed to do.

Notes on notation

It's important to get some nomenclature straight. In Figure 1, you see a start tag, which begins an enclosed area of text, known as an Item, according to the tag name. As in HTML, XML tags may include a list of attributes (consisting of an attribute name and an attribute value.) The Item defined by the tag ends with the end tag.

Not every tag encloses text. In HTML, the

tag means "line break" and contains no text. In XML, such elements aren't allowed. Instead, XML has empty tags, denoted by a slash before the final right-angle bracket in the tag. Figure 2 shows an empty tag from our XML recipe. Note that empty tags may have attributes. This empty tag example is standard XML shorthand for .

In addition to these notational differences from HTML, the structural rules of XML are more strict. Every XML document must be well-formed. What does that mean? Read on!

Ooh-la-la! Well-formed XML

The concept of well-formedness comes from mathematics: It's possible to write mathematical expressions that don't mean anything. For example, the expression

2 ( + + 5 (=) 9 > 7

looks (sort of) like math, but it isn't math because it doesn't follow the notational and structural rules for a mathematical expression (not on this planet, at least). In other words, the "expression" above isn't well-formed. Mathematical expressions must be well-formed before you can do anything useful with them, because expressions that aren't well-formed are meaningless.

A well-formed XML document is simply one that follows all of the notational and structural rules for XML. Programs that intend to process XML should reject any input XML that doesn't follow the rules for being well-formed. The most important of these rules are as follows: