XML untuk pemula mutlak

HTML dan World Wide Web ada di mana-mana. Sebagai contoh keberadaan mereka, saya akan pergi ke Amerika Tengah untuk Paskah tahun ini, dan jika saya mahu, saya dapat melayari laman web, membaca e-mel saya, dan juga melakukan perbankan dalam talian dari kafe Internet di Antigua Guatemala dan Belize City. (Namun, saya tidak berniat, kerana melakukannya akan memakan masa yang jauh dari tarikh saya dengan pohon palma dan kelapa yang dipenuhi rum.)

Namun, walaupun terdapat banyak dan populariti HTML, sangat terhad dalam apa yang dapat dilakukannya. Tidak apa-apa untuk menyebarkan dokumen tidak rasmi, tetapi HTML sekarang digunakan untuk melakukan perkara yang tidak pernah dirancang. Mencuba merancang sistem data tugas berat, fleksibel, yang dapat dikendalikan dari HTML adalah seperti cuba membina kapal induk dengan gergaji besi dan besi pemateri: alat (HTML dan HTTP) tidak sesuai dengan tugasnya.

Berita baiknya adalah bahawa banyak batasan HTML telah diatasi dalam XML, Bahasa Markah yang Dapat Diperluas. XML mudah difahami oleh sesiapa sahaja yang memahami HTML, tetapi jauh lebih hebat. Lebih daripada sekadar bahasa markup, XML adalah bahasa logam - bahasa yang digunakan untuk menentukan bahasa markup baru. Dengan XML, anda dapat membuat bahasa yang dibuat khusus untuk aplikasi atau domain anda.

XML akan melengkapkan, bukan mengganti, HTML. Walaupun HTML digunakan untuk memformat dan menampilkan data, XML mewakili makna kontekstual data.

Artikel ini akan memaparkan sejarah bahasa markup dan bagaimana XML wujud. Kami akan melihat data sampel dalam HTML dan beralih secara beransur-ansur ke dalam XML, menunjukkan mengapa ia menyediakan cara yang unggul untuk mewakili data. Kami akan meneroka sebab-sebab yang mungkin anda perlukan untuk mencipta bahasa markup tersuai, dan saya akan mengajar anda cara melakukannya. Kami akan membahas asas-asas notasi XML, dan cara memaparkan XML dengan dua jenis gaya bahasa yang berbeza. Kemudian, kita akan menyelami Model Objek Dokumen, alat yang kuat untuk memanipulasi dokumen sebagai objek (atau memanipulasi struktur objek sebagai dokumen, bergantung pada bagaimana anda melihatnya). Kami akan membahas bagaimana menulis program Java yang mengekstrak maklumat dari dokumen XML, dengan petunjuk ke program percuma yang berguna untuk bereksperimen dengan konsep baru ini. Akhirnya, kami 'Lihatlah sebuah syarikat Internet yang mendasarkan strategi teknologi utamanya pada XML dan Java.

Adakah XML untuk anda?

Walaupun artikel ini ditulis untuk siapa saja yang berminat dengan XML, artikel ini memiliki hubungan khusus dengan siri JavaWorld di XML JavaBeans. (Lihat Sumber untuk pautan ke artikel yang berkaitan.) Jika anda sudah membaca siri itu dan tidak cukup "mendapatkannya", artikel ini harus menjelaskan cara menggunakan XML dengan kacang. Jika anda sedang mendapat ia, artikel ini berfungsi sebagai bahagian teman yang sempurna untuk siri JavaBeans XML, kerana ia merangkumi topik-topik di dalamnya tidak disentuh. Dan, jika anda adalah salah satu daripada beberapa orang yang bernasib baik yang masih mempunyai artikel XML JavaBeans yang dinantikan, saya mengesyorkan agar anda membaca artikel ini terlebih dahulu sebagai bahan pengantar.

Catatan mengenai Java

Terdapat begitu banyak aktiviti XML baru-baru ini di dunia komputer sehingga artikel sepanjang ini hanya dapat melangkau permukaan. Namun, inti dari artikel ini adalah untuk memberi anda konteks yang anda perlukan untuk menggunakan XML dalam rancangan program Java anda. Artikel ini juga merangkumi bagaimana XML beroperasi dengan teknologi Web yang ada, kerana banyak pengaturcara Java bekerja dalam lingkungan seperti itu.

XML membuka Internet dan pengaturcaraan Java ke fungsi mudah alih dan bukan browser. XML membebaskan kandungan Internet dari penyemak imbas dengan cara yang sama Java membebaskan tingkah laku program dari platform. XML menjadikan kandungan Internet tersedia untuk aplikasi sebenar.

Java adalah platform yang sangat baik untuk menggunakan XML, dan XML adalah representasi data yang luar biasa untuk aplikasi Java. Saya akan menunjukkan beberapa kekuatan Java dengan XML semasa kita mengikuti.

Mari kita mulakan dengan pelajaran sejarah.

Asal-usul bahasa markup

HTML yang kita semua tahu dan sukai (baik, yang kita tahu, bagaimanapun) pada asalnya dirancang oleh Tim Berners-Lee di CERN ( le Conseil Européen pour la Recherche Nucléaire, atau Makmal Eropah untuk Fizik Partikel) di Geneva untuk membolehkan kutu buku fizik ( dan juga bukan pelacur) untuk berkomunikasi antara satu sama lain. HTML dilancarkan pada bulan Disember 1990 di dalam CERN, dan tersedia untuk umum pada musim panas tahun 1991 untuk kita semua. CERN dan Berners-Lee memberikan spesifikasi untuk HTML, HTTP, dan URL, dalam tradisi lama berkongsi dan menikmati Internet.

Berners-Lee mendefinisikan HTML dalam SGML, Bahasa Peningkatan Umum Standard. SGML, seperti XML, adalah bahasa logam - bahasa yang digunakan untuk menentukan bahasa lain. Setiap bahasa yang ditentukan disebut aplikasi SGML. HTML adalah aplikasi SGML.

SGML muncul dari penyelidikan yang dilakukan terutamanya di IBM mengenai perwakilan dokumen teks pada akhir 60-an. IBM mencipta GML ("General Markup Language"), bahasa pendahuluan kepada SGML, dan pada tahun 1978 American National Standards Institute (ANSI) membuat versi pertama SGML. Standard pertama dikeluarkan pada tahun 1983, dengan draf standard dikeluarkan pada tahun 1985, dan standard pertama diterbitkan pada tahun 1986. Menariknya, standard SGML pertama diterbitkan menggunakan sistem SGML yang dikembangkan oleh Anders Berglund di CERN, organisasi yang, sebagai kami telah melihat, memberi kami HTML dan Web.

SGML digunakan secara meluas di industri dan kerajaan besar seperti di syarikat aeroangkasa, automotif, dan telekomunikasi besar. SGML digunakan sebagai standard dokumen di Jabatan Pertahanan Amerika Syarikat dan Perkhidmatan Hasil Dalam Negeri. (Bagi pembaca di luar AS, IRS adalah orang yang tidak bertanggungjawab.)

Albert Einstein mengatakan bahawa semuanya harus dibuat sesederhana mungkin, dan tidak lebih sederhana. Sebab SGML tidak dijumpai di lebih banyak tempat adalah ia sangat canggih dan kompleks. Dan HTML, yang anda dapati di mana-mana sahaja, sangat mudah; untuk banyak aplikasi, terlalu mudah.

HTML: Semua bentuk dan tidak ada isi

HTML adalah bahasa yang dirancang untuk "membicarakan" dokumen: tajuk, tajuk, kapsyen, fon, dan sebagainya. Ini sangat berorientasikan struktur dokumen dan persembahan.

Diakui, para seniman dan penggodam dapat melakukan keajaiban dengan alat yang agak kusam yang disebut HTML. Tetapi HTML mempunyai kelemahan serius yang menjadikannya tidak sesuai untuk merancang sistem maklumat yang fleksibel, kuat dan evolusi. Berikut adalah beberapa aduan utama:

  • HTML tidak dapat diperluas

    Bahasa markup yang boleh diperluaskan akan membolehkan pembangun aplikasi menentukan tag khusus untuk situasi khusus aplikasi. Kecuali anda adalah gorila seberat 600 paun (dan mungkin juga tidak) anda tidak boleh meminta semua pengeluar penyemak imbas untuk melaksanakan semua tanda penanda yang diperlukan untuk aplikasi anda. Oleh itu, anda terperangkap dengan apa yang akan dibuat oleh pembuat perisian penyemak imbas yang besar atau W3C (World Wide Web Consortium). Apa yang kita perlukan adalah bahasa yang membolehkan kita membuat tag markup kita sendiri tanpa perlu menghubungi pengeluar penyemak imbas.

  • HTML sangat berpusatkan paparan

    HTML adalah bahasa yang baik untuk tujuan paparan, melainkan anda memerlukan banyak pemformatan atau kawalan transformasi yang tepat (dalam hal ini bau). HTML mewakili campuran struktur logik dokumen (tajuk, perenggan, dan semacamnya) dengan tag persembahan (tebal, penjajaran gambar, dan sebagainya). Oleh kerana hampir semua tag HTML ada kaitannya dengan cara memaparkan maklumat dalam penyemak imbas, HTML tidak berguna untuk aplikasi rangkaian umum lain - seperti replikasi data atau perkhidmatan aplikasi. Kami memerlukan cara untuk menyatukan fungsi umum ini dengan paparan, sehingga pelayan yang sama yang digunakan untuk mencari data juga dapat, misalnya, melakukan fungsi bisnis perusahaan dan beroperasi dengan sistem warisan.

  • HTML biasanya tidak boleh digunakan semula secara langsung

    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:

  • No unclosed tags

    You can get away with all kinds of wacko stuff in HTML. For example, in most HTML browsers, you can "open" a list item with

  • and never "close" it with
  • . The browser just figures out where the would be and automatically inserts it for you. XML doesn't allow this kind of sloppiness. Every start tag must have a corresponding end tag. This is because part of the information in an XML file has to do with how different elements of information relate to one another, and if the structure is ambiguous, so is the information. So, XML simply doesn't allow ambiguous structure. This nonambiguous structure also allows XML documents to be processed as data structures (trees), as I'll explain shortly in the discussion of the Document Object Model.

  • No overlapping tags

    A tag that opens inside another tag must close before the containing tag closes. For example, the sequence

    Let's call the whole thing off

    isn't well-formed because opens inside of but doesn't close inside of . The correct sequence must be

    Let's call the whole thing off

    In other words, the structure of the document must be strictly hierarchical.

  • Attribute values must be enclosed in quotes

    Unlike HTML, XML doesn't allow "naked" attribute values (i.e., HTML tags like

    , where there are no quotes around the attribute value). Every attribute value must have quotes (

  • The text characters (), and (") must always be represented by 'character entities'

    To represent these three characters (left-angle bracket, right-angle bracket, and double quotes) in the text part of the XML (not in the markup), you must use the special character entities (

    <

    ), (

    >

    ), and (

    "

    ), respectively. These characters are special characters for XML. An XML file using, say, the double quote character in the text enclosed in tags in an XML file isn't well-formed, and correctly designed XML parsers will produce an error for such input.

  • 'Well-formed' means 'parsable'

    A generic XML parser is a program or class that can read any well-formed XML at its input. Many vendors now offer XML parsers in Java for free; (you'll find links to these packages in Resources at the bottom of this article). XML parsers recognize well-formed documents and produce error messages (much like a compiler would) when they receive input that isn't well-formed. As we'll see, this functionality is very handy for the programmer: You simply call the parser you've selected and it takes care of the error detection and so on. While all XML parsers check the well-formedness of documents (meaning, as we've seen, that all the tags make sense, are nested properly, and so on), validating XML parsers go one step further. Validating parsers also confirm whether the document is valid; that is, that the structure and number of tags make sense.

    For example, most browsers will display a document that (nonsensically) has two elements, but how can this be? Only one title or no title makes sense.

    For another example, imagine that in Listing 3 the "cottage cheese" ingredient looked like this:

      500 9 Cottage cheese  

    This XML document is certainly well-formed, but it doesn't make sense. It isn't structurally valid. It is nonsense for a to contain a <Qty>. What's the of this ?

    The problem is, we have a document that's well-formed, but it isn't very useful because the XML doesn't make sense. We need a way to specify what makes an XML document valid. For example, how can we specify that a tag may contain only text (and not any other elements) and report as errors any other case?

    The answer to this question lies in something called the document type definition, which we'll look at next.





    ). #####