Tài liệu XML by Example- P5 doc - Pdf 87

Figure 6.10: XMetaL, a WYSIWYG editor
XSLFO
CSS is a simple and efficient styling mechanism. However, it is limited to
styling a document, it cannot reorganize or otherwise process them. CSS
cannot build a table of contents or extract an index as XSLT.
XSLT and CSS
Nothing prevents you from combining XSLT with CSS. Listing 6.5 shows
how an XSLT style sheet can attach a CSS style sheet to a document and
create a table of contents in XML. Figure 6.11 shows the result in a
browser.
Listing 6.5: XSLT Style Sheet
<?xml version=”1.0” encoding=”ISO-8859-1”?>
<xsl:stylesheet
xmlns:xsl=” /><xsl:template match=”/”>
<xsl:processing-instruction name=”xml-stylesheet”>
href=”article.css” type=”text/css”
</xsl:processing-instruction>
<xsl:apply-templates/>
</xsl:template>
185
XSLFO
EXAMPLE
continues
08 2429 CH06 2.29.2000 2:22 PM Page 185
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Listing 6.5: continued
<xsl:template match=”keywords”>
<keywords><xsl:apply-templates/></keywords>
<section>
<title>Table of Contents</title>
<xsl:for-each select=”/article/section/title”>

If using CSS in combination with XSLT makes sense, why not offer CSS
features in XSLT? This is the reasoning behind XSLFO. XSLFO essentially
ports the CSS properties to XSL.
Listing 6.6 is a simple XSLFO style sheet. Figure 6.13 shows the result in
InDelv, currently the only browser on the market to support XSLFO.
Listing 6.6: A Simple XSLFO Style Sheet
<?xml version=”1.0”?>
<xsl:stylesheet
xmlns:xsl=” />xmlns:fo=” /><xsl:template match=”/”>
<fo:display-sequence
start-indent=”5pt”
end-indent=”5pt”
font-size=”10pt”
font-family=”serif”>
EXAMPLE
continues
08 2429 CH06 2.29.2000 2:22 PM Page 187
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Listing 6.5: continued
<xsl:apply-templates/>
</fo:display-sequence>
</xsl:template>
<xsl:template match=”p”>
<fo:block>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match=”title”>
<fo:block
font-size=”13pt”

object properties are word for word taken from the CSS specification.
XLSFO also includes formatting objects specifically designed for XML; for
example,
fo:inline-link
creates a hyperlink. It has no equivalent in CSS.
This section is a very brief look at XSLFO because, at the time of this
writing, XSLFO has not achieved significant market acceptance. The
concepts, however, are very close to CSS.
What’s Next
Now that you know how to create and view XML documents, the next three
chapters will take you one step further and teach you how to manipulate
and create XML documents from a scripting or programming language.
189
What's Next
OUTPUT
08 2429 CH06 2.29.2000 2:22 PM Page 189
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
09 2429 CH07 2.29.2000 2:22 PM Page 190
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
7
The Parser and DOM
The previous chapters showed how to view and transform XML documents.
Style sheet is a powerful technology but it is limited to viewing and trans-
forming. When you have more specific needs, you need to turn to program-
ming. This chapter introduces how to read XML documents from
JavaScript or Java.
In this chapter, you learn
• what an XML parser is
• how to interface a parser with an application
• what DOM, the Document Object Model, is

ets. There might be entities in the price list. The application must read and
interpret the DTD to be able to resolve entities. While it’s reading the DTD,
it might as well read element definitions and validate the document.
✔ For more information on how the DTD influences the document, see the section
“Standalone Documents” in Chapter 3 (page 79).
What about other XML features: character encodings, namespaces, param-
eter entities? And did you consider errors? How does your software recover
from a missing closing tag?
The XML syntax is simple. Yet, it’s an extensible syntax so XML applica-
tions have to be ready to cope with many options. As it turns out, writing a
software library to read XML files is a one-month assignment. If you were
to write such a library, you would be writing your own parser.
Is it productive to spend one month writing a parser library when you need
only half a day’s work to process the data? Of course not.
That’s why developers download a parser from the Internet or use the one
that ships with the development tool. This is the common definition of a
parser: off-the-shelf components that isolate programmers from the
specifics of the XML syntax.
If you are not convinced yet and if you’d rather write your own XML parser,
consider this: No programmer in his/her right mind (except those working
for Oracle, Sybase, Informix, and the like) would write low-level database
drivers. It makes more sense to use the drivers that ship with the database.
Likewise, no programmer should spend time decoding XML files—it makes
more sense to turn to existing parsers.
192
Chapter 7: The Parser and DOM
09 2429 CH07 2.29.2000 2:22 PM Page 192
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
NOTE
The word parser comes from compilers. In a compiler, a parser is the module that

• The parser deals with the XML file.
• The application consumes the content of the file through the parser.
193
The Parser and the Application
09 2429 CH07 2.29.2000 2:22 PM Page 193
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 7.1: Architecture of an XML program
Note that the application can be very simple (such as printing information
on the screen), or quite complex (such as a browser or an editor).
This chapter and the next one concentrate on the dotted line between the
two elements. This is the interface, or the communication path, between
the parser and the application.
The parser and the application must share a common model for XML data.
In practice, the common model is always some variation on a tree in mem-
ory that matches the tree in the XML document.
The parser reads the XML document and populates the tree in memory.
This tree built by the parser is an exact match of the tree in the XML docu-
ment. The application manipulates it as if it were the XML document. In
fact, for the application, it is the XML document.
Object-Based Interface
There are two basic ways to interface a parser with an application: using
object-based interfaces and using event-based interfaces. In practice, the
two approaches are more complementary than competitive.
Using an object-based interface, the parser explicitly builds a tree of objects
that contains all the elements in the XML document.
This is probably the most natural interface for the application because it is
handed a tree in memory that exactly matches the file on disk.
Obviously, it’s more convenient for the application to work with the tree in
memory, if only because it doesn’t have to worry about the XML syntax.
Furthermore, if using a validating parser, the tree may have been validated

</product>
</products>
The parser reads this document and gradually builds a tree of objects that
matches the document. Figure 7.3 illustrates how the tree is being built.
Figure 7.3: Building the tree of objects
09 2429 CH07 2.29.2000 2:23 PM Page 195
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
When the XML parser reads the document in Listing 7.1, it recognizes that
the top-level element is named
products
. Therefore, it constructs an object
to represent the
products
element.
The next element is a
product
. The parser creates another object to repre-
sent the
product
element. Because this is a tree, it attaches the
product
object to the
products
object.
The next element is a
name
. Again, the parser creates an object for the
name
and adds it to the tree being built.
In the

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
At first sight, this solution is less natural for the application because it is
not given an explicit tree that matches the file. Instead, the application has
to listen to events and determine which tree is being described.
In practice, both forms of interfaces are helpful but they serve different
goals. Object-based interfaces are ideal for applications that manipulate
XML documents such as browsers, editors, XSL processors, and so on.
Event-based interfaces are geared toward applications that maintain their
own data structure in a non-XML format. For example, event-based inter-
faces are well adapted to applications that import XML documents in data-
bases. The format of the application is the database schema, not the XML
schema. These applications have their own data structure and they map
from an XML structure to their internal structure.
An event-based interface is also more efficient because it does not explicitly
build the XML tree in memory. Fewer objects are required and less memory
is being used.
✔ Chapter 8 discusses event-based interfaces in greater detail (“Alternative API: SAX,”
page 231).
The Need for Standards
Ideally, the interface between the parser and the application should be a
standard. A standard interface enables you to write software using one
parser and to deploy the software with another parser.
Again, there is a similarity with databases. Relational databases use SQL
as their standard interface. Because they all share the same interface,
developers can write software with one database and later move to another
database (for price reasons, availability, and so on) without changing the
application.
That’s the theory, at least. In practice, small differences, vendor extensions,
and other issues mean that moving from one vendor to another requires
more work than just recompiling the application. At the minimum, even if

Originally, the W3C developed DOM for browsers. DOM grew out of an
attempt to unify the object models of Netscape Navigator 3 and Internet
Explorer 3. The DOM recommendation supports both XML and HTML doc-
uments.
The current recommendation is DOM level 1. Level 1 means that it fully
specifies well-formed documents. DOM level 2 is under development and it
will support valid documents—that is, the DTDs.
DOM’s status as the official recommendation from the W3C means that
most parsers support it. DOM is also implemented in browsers, meaning
that you can write DOM applications with a browser and JavaScript.
As you can imagine, DOM has defined classes of objects to represent every
element in an XML file. There are objects for elements, attributes, entities,
text, and so on. Figure 7.5 shows the DOM hierarchy.
Getting Started with DOM
Let’s see, through examples, how to use a DOM parser. DOM is imple-
mented in a Web browser so these examples run in a browser. At the time
of this writing, Internet Explorer 5.0 is the only Web browser to support the
standard DOM for XML. Therefore, make sure you use Internet Explorer
5.0.
198
Chapter 7: The Parser and DOM
09 2429 CH07 2.29.2000 2:23 PM Page 198
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 7.5: The hierarchy in DOM
A DOM Application
Listing 7.2 is the HTML page for a JavaScript application to convert prices
from U.S. dollars to Euros. The price list is an XML document. The applica-
tion demonstrates how to use DOM.
A slightly modified version of this page (essentially, putting up a better
face) could be used on an electronic shop. International shoppers could

HTML file. Listing 7.3 is conversion.js.
<SCRIPT LANGUAGE=”JavaScript” SRC=”conversion.js”></SCRIPT>
Listing 7.3: Conversion.js, the JavaScript File to Convert Prices
function convert(form,xmldocument)
{
var fname = form.fname.value,
output = form.output,
rate = form.rate.value;
output.value = “”;
var document = parse(fname,xmldocument),
topLevel = document.documentElement;
searchPrice(topLevel,output,rate);
}
function parse(uri,xmldocument)
{
xmldocument.async = false;
xmldocument.load(uri);
if(xmldocument.parseError.errorCode != 0)
alert(xmldocument.parseError.reason);
return xmldocument;
}
function searchPrice(node,output,rate)
{
if(node.nodeType == 1)
{
if(node.nodeName == “price”)
output.value += (getText(node) * rate) + “\r”;
200
Chapter 7: The Parser and DOM
Listing 7.2: continued

Rate: <INPUT TYPE=”TEXT” NAME=”rate” VALUE=”0.95274” SIZE=”4”>
It also defines a read-only text area that serves as output:
<TEXTAREA NAME=”output” ROWS=”10” COLS=”50” READONLY> </TEXTAREA>
Finally, it defines an XML island. XML islands are mechanisms used to
insert XML in HTML documents. In this case, XML islands are used to
access Internet Explorer’s XML parser. The price list is loaded into the
island.
Note that XML island is specific to Internet Explorer 5.0. It would not work
with another browser. We will see why we have to use browser-specific code
in a moment.
<xml id=”xml”></xml>
The
“Convert”
button in the HTML file calls the JavaScript function
convert(),
which is the conversion routine.
convert()
accepts two param-
eters, the form and the XML island:
<INPUT TYPE=”BUTTON” VALUE=”Convert” ONCLICK=”convert(controls,xml)”>
The script retrieves the filename and exchange rate from the form. It com-
municates with the XML parser through the XML island.
DOM Node
The core object in DOM is the
Node
. Nodes are generic objects in the tree
and most DOM objects are derived from nodes. There are specialized ver-
sions of nodes for elements, attributes, entities, text, and so on.
Node
defines several properties to help you walk through the tree:

nextSibling
is the
Node
immediately following the current one.

attributes
is the list of attributes, if the current
Node
has any.
In addition,
Node
defines two properties to manipulate the underlying
object:
202
Chapter 7: The Parser and DOM
09 2429 CH07 2.29.2000 2:23 PM Page 202
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

nodeName
is the name of the
Node
(for an element, it’s the tag name).

nodeValue
is the value of the
Node
(for a text node, it’s the text).
Table 7.1:
nodeType
code

.
Document
inherits from
Node
so it can be inserted in a tree.
Document
inherits most properties from
Node
and adds only two new properties:
203
Getting Started with DOM
EXAMPLE
09 2429 CH07 2.29.2000 2:23 PM Page 203
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

documentElement
is the topmost element in the document.

doctype
is the Document Type. DOM level 1 does not fully specify the
document type. This will be done in DOM level 2.
Document
is similar to the root in XSL path. It’s an object one step before
the topmost element.
To return a tree, the parser returns a
Document
object. From the
Document
object, it is possible to access the complete document tree.
CAUTION

load()
loads the document.
Finally, it checks for errors while parsing. The
parseError
property holds
information about parsing errors.
Walking the Element Tree
To extract information or otherwise manipulate the document, the applica-
tion walks the tree. You have already seen this happening with the XSL
processor.
Essentially, you write an application that visits each element in the tree.
This is easy with a recursive algorithm. To visit a node:
204
Chapter 7: The Parser and DOM
EXAMPLE
09 2429 CH07 2.29.2000 2:23 PM Page 204
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status