Stage 2 · Topic 2 - JSP · Session 8: Working with XML
WebContent/xml and books.xml — then
NextThe file is created successfully.
WebContent/xml so that the file ends up in
the deployed application and can be fetched over HTTP from a JSP. An XML
file sitting in src would be copied nowhere useful.
One root element, and every element has a start tag and a close tag. The first line states the XML version number, which is 1.
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
| Element | Contains | Appears |
|---|---|---|
<books> | the whole catalogue | once — this is the root |
<book> | one title | twice |
<name> | the title | once per book |
<author> | who wrote it | once per book |
<price> | the price, as text | once per book |
<price>100</price>
is a piece of text that happens to look like a number. Nothing in the file
says it is an integer, and 0100 or one hundred
would be equally legal. Converting it is the job of the program —
see s8-04, which has to read the text and
call Integer.parseInt() itself.
books <- root
|
+-- book <- first child
| +-- name : Padam History
| +-- author : ZARA
| +-- price : 100
|
+-- book <- second child
+-- name : Great Mistry
+-- author : NUHA
+-- price : 2000
Reading a tree like this is what an XML parser gives you, and what XPath — the query language built into XML — is for. The most common paths for this document are:
| XPath | Selects |
|---|---|
/books | the root element |
/books/book | every book element, in order |
/books/book[1] | the first book only |
//name | every name anywhere in the document |
//book[price > 500] | books costing more than 500 |
//book[author='ZARA']/name | the title written by ZARA |
// means “anywhere below”, so
//name is short for
/descendant-or-self::node()/child::name. It is convenient and
it is slow on a large document; when speed matters, spell out the full
path from the root instead.
Open xml/books.xml in any modern browser and it renders the tree itself: a collapsible outline with each element name and its text. That built-in viewer is the quickest way to check that a document is well-formed — if the tree appears, it parsed; if you get an error, the browser points at the offending line.
books.xml:
<?xml-stylesheet type="text/xsl" href="style.xsl"?>That processing instruction names the stylesheet, and every browser that supports XSLT will then show the formatted output. It is also what lets s8-05 and s8-06 do the same thing from a JSP — though a JSP gives you the choice of many stylesheets at runtime, which a processing instruction cannot do.