XML Advanced-from w3schools.com

XML Namespaces

back next


XML Namespaces provide a method to avoid element name conflicts.


Name Conflicts

Since element names in XML are not fixed, very often a name conflict will occur when two different documents use the same names describing two different types of elements.

This XML document carries information in a table:

1<table>
2<tr>
3<td>Apples</td>
4<td>Bananas</td>
5</tr>
6</table>

This XML document carries information about a table (a piece of furniture):

1<table>
2<name>African Coffee Table</name>
3<width>80</width>
4<length>120</length>
5</table>

If these two XML documents were added together, there would be an element name conflict because both documents contain a

  1<table> element with different content and definition. 
  2
  3* * *
  4
  5##  Solving Name Conflicts using a Prefix 
  6
  7This XML document carries information in a table: 
  8    
  9    
 10    <h:table>
 11<h:tr>
 12<h:td>Apples</h:td>
 13<h:td>Bananas</h:td>
 14</h:tr>
 15</h:table>  
 16  
 17---  
 18  
 19This XML document carries information about a piece of furniture: 
 20    
 21    
 22    <f:table>
 23<f:name>African Coffee Table</f:name>
 24<f:width>80</f:width>
 25<f:length>120</f:length>
 26</f:table>  
 27  
 28---  
 29  
 30Now the element name conflict is gone because the two documents use a different name for their <table> element (<h:table> and <f:table>). 
 31
 32By using a prefix, we have created two different types of <table> elements. 
 33
 34* * *
 35
 36##  Using Namespaces 
 37
 38This XML document carries information in a table: 
 39    
 40    
 41    <h:table xmlns:h="http://www.w3.org/TR/html4/">
 42<h:tr>
 43<h:td>Apples</h:td>
 44<h:td>Bananas</h:td>
 45</h:tr>
 46</h:table>  
 47  
 48---  
 49  
 50This XML document carries information about a piece of furniture: 
 51    
 52    
 53    <f:table xmlns:f="http://www.w3schools.com/furniture">
 54<f:name>African Coffee Table</f:name>
 55<f:width>80</f:width>
 56<f:length>120</f:length>
 57</f:table>  
 58  
 59---  
 60  
 61Instead of using only prefixes, an **xmlns attribute** has been added to the <table> tag to give the element prefix a **qualified name** associated with a **namespace** . 
 62
 63* * *
 64
 65##  The Namespace Attribute 
 66
 67The namespace attribute is placed in the start tag of an element and has the following syntax: 
 68    
 69    
 70    xmlns:namespace-prefix="namespace"  
 71  
 72---  
 73  
 74In the examples above, the namespace itself is defined using an Internet address: 
 75    
 76    
 77    xmlns:f="http://www.w3schools.com/furniture"  
 78  
 79---  
 80  
 81The W3C namespace specification states that the namespace itself should be a **Uniform Resource Identifier (URI)** . 
 82
 83When a namespace is defined in the start tag of an element, all child elements with the same prefix are associated with the same namespace. 
 84
 85Note that the address used to identify the namespace, is not used by the parser to look up information. The only purpose is to give the namespace a unique name. However, very often companies use the namespace as a pointer to a real Web page containing information about the namespace.   
 86Try to go to http://www.w3.org/TR/html4/ . 
 87
 88* * *
 89
 90##  Uniform Resource Identifiers 
 91
 92A **Uniform Resource Identifier** (URI) is a string of characters which identifies an Internet Resource. The most common URI is the **Uniform Resource Locator** (URL) which identifies an Internet domain address. Another, not so common type of URI is the **Universal Resource Name** (URN). In our examples we will only use URLs. 
 93
 94Since our furniture example uses an internet address to identify its namespace, we can be sure that our namespace is unique. 
 95
 96* * *
 97
 98##  Default Namespaces 
 99
100Defining a default namespace for an element saves us from using prefixes in all the child elements. It has the following syntax: 
101    
102    
103    <element xmlns="namespace">  
104  
105---  
106  
107This XML document carries information in a table: 
108    
109    
110    <table xmlns="http://www.w3.org/TR/html4/">
111<tr>
112<td>Apples</td>
113<td>Bananas</td>
114</tr>
115</table>  
116  
117---  
118  
119This XML document carries information about a piece of furniture: 
120    
121    
122    <table xmlns="http://www.w3schools.com/furniture">
123<name>African Coffee Table</name>
124<width>80</width>
125<length>120</length>
126</table>  
127  
128---  
129  
130
131
132* * *
133
134##  Namespaces in Real Use 
135
136When you start using XSL, you will soon see namespaces in real use. XSL style sheets are used to transform XML documents into other formats like HTML. 
137
138If you take a close look at the XSL document below, you will see that most of the tags are HTML tags. The tags that are not HTML tags have the prefix xsl, identified by the namespace " http://www.w3.org/TR/xsl ": 
139    
140    
141    <?xml version="1.0" encoding="ISO-8859-1"?>
142<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/xsl">
143<xsl:template match="/">
144<html>
145<body>
146<table bgcolor="yellow" border="2">
147<tr>
148<th>Title</th>
149<th>Artist</th>
150</tr>
151<xsl:for-each select="CATALOG/CD">
152<tr>
153<td><xsl:value-of select="TITLE"></xsl:value-of></td>
154<td><xsl:value-of select="ARTIST"></xsl:value-of></td>
155</tr>
156</xsl:for-each>
157</table>
158</body>
159</html>
160</xsl:template>
161</xsl:stylesheet>  
162  
163---  
164  
165
166
167* * *
168
169#  XML CDATA 
170
171![back](http://www.w3schools.com/images/btn_previous.gif) ![next](http://www.w3schools.com/images/btn_next.gif)
172
173* * *
174
175All text in an XML document will be **parsed** by the parser. 
176
177Only text inside a CDATA section is **ignored** by the parser. 
178
179* * *
180
181##  Parsed Data 
182
183**XML parsers normally parse all the text in an XML document.**
184
185When an XML element is parsed, the text between the XML tags is also parsed: 
186    
187    
188    <message>This text is also parsed</message>  
189  
190---  
191  
192The parser does this because XML elements can contain other elements, as in this example, where the <name> element contains two other elements (first and last): 
193    
194    
195    <name><first>Bill</first><last>Gates</last></name>  
196  
197---  
198  
199and the parser will break it up into sub-elements like this: 
200    
201    
202    <name>
203<first>Bill</first>
204<last>Gates</last>
205</name>  
206  
207---  
208  
209
210
211* * *
212
213##  Escape Characters 
214
215**Illegal XML characters have to be replaced by entity references.**
216
217If you place a character like "&lt;" inside an XML element, it will generate an error because the parser interprets it as the start of a new element. You cannot write something like this: 
218    
219    
220    <message>if salary &lt; 1000 then</message>  
221  
222---  
223  
224To avoid this, you have to **replace** the "&lt;" character with an **entity reference** , like this: 
225    
226    
227    <message>if salary &lt; 1000 then</message>  
228  
229---  
230  
231There are 5 predefined entity references in XML: 
232
233&lt;  |  &lt; |  less than   
234---|---|---  
235&gt;  |  &gt; |  greater than   
236&amp;  |  &amp; |  ampersand   
237'  |  '  |  apostrophe   
238"  |  "  |  quotation mark   
239  
240Entity references always start with the "&amp;" character and end with the ";" character. 
241
242**Note:** Only the characters "&lt;" and "&amp;" are strictly illegal in XML. Apostrophes, quotation marks and greater than signs are legal, but it is a good habit to replace them. 
243
244* * *
245
246##  CDATA 
247
248**Everything inside a CDATA section is ignored by the parser.**
249
250If your text contains a lot of "&lt;" or "&amp;" characters - as program code often does - the XML element can be defined as a CDATA section. 
251
252A CDATA section starts with " ** <![CDATA[ ** " and ends with " **]]> ** ": 
253    
254    
255    <script>
256    <![CDATA[
257    function matchwo(a,b)
258    {
259    if (a < b && a < 0) then
260       {
261       return 1
262       }
263    else
264       {
265       return 0
266       }
267    }
268    ]]>
269    </script>  
270  
271---  
272  
273In the previous example, everything inside the CDATA section is ignored by the parser. 
274
275###  Notes on CDATA sections: 
276
277A CDATA section cannot contain the string "]]&gt;", therefore, nested CDATA sections are not allowed. 
278
279Also make sure there are no spaces or line breaks inside the "]]&gt;" string. 
280
281* * *
282
283#  XML Encoding 
284
285![back](http://www.w3schools.com/images/btn_previous.gif) ![next](http://www.w3schools.com/images/btn_next.gif)
286
287* * *
288
289XML documents can contain foreign characters like Norwegian æøå, or French êèé. 
290
291To let your XML parser understand these characters, you should save your XML documents as Unicode. 
292
293* * *
294
295##  Windows 95/98 Notepad 
296
297**Windows 95/98 Notepad cannot save files in Unicode format.**
298
299You can use Notepad to edit and save XML documents that contain foreign characters (like Norwegian or French æøå and êèé), 
300    
301    
302    <?xml version="1.0"?>
303<note>
304<from>Jani</from>
305<to>Tove</to>
306<message>Norwegian: æøå. French: êèé</message>
307</note>  
308  
309---  
310  
311But if you save the file and  open it with IE 5.0  , you will get an **ERROR MESSAGE** . 
312
313* * *
314
315##  Windows 95/98 Notepad with Encoding 
316
317**Windows 95/98 Notepad files must be saved with an encoding attribute.**
318
319To avoid this error you can add an encoding attribute to your XML declaration, but you cannot use Unicode. 
320
321The encoding below (  open it with IE 5.0  ), will NOT give an error message: 
322    
323    
324    <?xml version="1.0" encoding="windows-1252"?>  
325  
326---  
327  
328The encoding below (  open it with IE 5.0  ), will NOT give an error message: 
329    
330    
331    <?xml version="1.0" encoding="ISO-8859-1"?>  
332  
333---  
334  
335The encoding below (  open it with IE 5.0  ), will NOT give an error message: 
336    
337    
338    <?xml version="1.0" encoding="UTF-8"?>  
339  
340---  
341  
342The encoding below (  open it with IE 5.0  ), WILL give an error message: 
343    
344    
345    <?xml version="1.0" encoding="UTF-16"?>  
346  
347---  
348  
349
350
351* * *
352
353##  Windows 2000 Notepad 
354
355**Windows 2000 Notepad can save files as Unicode.**
356
357The Notepad editor in Windows 2000 supports Unicode. If you select to save this XML file as Unicode (note that the document does not contain any encoding attribute): 
358    
359    
360    <?xml version="1.0"?>
361<note>
362<from>Jani</from>
363<to>Tove</to>
364<message>Norwegian: æøå. French: êèé</message>
365</note>  
366  
367---  
368  
369The following file;  note_encode_none_u.xml  , will NOT give an error message if you open it with IE 5.0, but if you open it with Netscape 6.2, you WILL get an error message. 
370
371* * *
372
373##  Windows 2000 Notepad with Encoding 
374
375**Windows 2000 Notepad files saved as Unicode use "UTF-16" encoding.**
376
377If you add an encoding attribute to XML files saved as Unicode, windows encoding values will generate an error. 
378
379This encoding (  open it  ), will NOT give an error message: 
380    
381    
382    <?xml version="1.0" encoding="windows-1252"?>  
383  
384---  
385  
386This encoding (  open it  ), will NOT give an error message: 
387    
388    
389    <?xml version="1.0" encoding="ISO-8859-1"?>  
390  
391---  
392  
393This encoding (  open it  ), will NOT give an error message: 
394    
395    
396    <?xml version="1.0" encoding="UTF-8"?>  
397  
398---  
399  
400The following file;  note_encode_utf16_u.xml  , will NOT give an error message if you open it with IE 5.0, but if you open it with Netscape 6.2, you WILL get an error message. 
401    
402    
403    <?xml version="1.0" encoding="UTF-16"?>  
404  
405---  
406  
407
408
409* * *
410
411##  Error Messages 
412
413If you try to load an XML document into Internet Explorer 5, you can get two different errors indicating encoding problems: 
414
415**An invalid character was found in text content.**
416
417You will get this error message if a character in the XML document does not match the encoding attribute. Normally you will get this error message if your XML document contains "foreign" characters, and the file was saved with a single-byte encoding editor like Notepad, and no encoding attribute was specified.   
418  
419**Switch from current encoding to specified encoding not supported.**
420
421You will get this error message if your file was saved as Unicode/UTF-16 but the encoding attribute specified a single-byte encoding like Windows-1252, ISO-8859-1 or UTF-8. You can also get this error message if your document was saved with single-byte encoding, but the encoding attribute specified a double-byte encoding like UTF-16. 
422
423* * *
424
425##  Conclusion 
426
427The conclusion is that the encoding attribute has to specify the encoding used when the document was saved. My best advice to avoid errors is: 
428
429  * **Use an editor that supports encoding.**
430  * **Make sure you know what encoding it uses.**
431  * **Use the same encoding attribute in your XML documents.**
432
433
434
435* * *
436
437#  A Simple XML Server 
438
439![back](http://www.w3schools.com/images/btn_previous.gif) ![next](http://www.w3schools.com/images/btn_next.gif)
440
441* * *
442
443XML can be generated on a server without any installed XML controls. 
444
445* * *
446
447##  Storing XML on the Server 
448
449**XML files can be stored on your Internet server.**
450
451XML files can be stored on your Internet server, in exactly the same way as HTML files. 
452
453Start up your Notepad editor and write the following lines: 
454    
455    
456    <?xml version="1.0" encoding="ISO-8859-1"?>
457<note>
458<from>Jani</from>
459<to>Tove</to>
460<message>Remember me this weekend</message>
461</note>  
462  
463---  
464  
465All you have to do is to save the file on your Internet server with a proper name like "note.xml", before the XML document is ready to use. 
466
467**Note:** The XML file must be in the same directory (folder) as your HTML files, and the MIME type of XML files should be set to text/xml. 
468
469* * *
470
471##  Generating XML with ASP 
472
473**XML can be generated on a server without any installed XML software.**
474
475To generate an XML response from your server - simply write the following code and save it as an ASP file on your web server : 
476    
477    
478    ```
479
480    response.ContentType="text/xml"
481    
482    response.Write("&lt;?xml version='1.0' encoding='ISO-8859-1'?&gt;")
483    response.Write("&lt;note&gt;")
484    response.Write("&lt;from&gt;Jani&lt;/from&gt;")
485    response.Write("&lt;to&gt;Tove&lt;/to&gt;")
486    response.Write("&lt;message&gt;Remember me this weekend&lt;/message&gt;")
487    response.Write("&lt;/note&gt;")
488    

Note that the content type of the response must be set to XML. See how the ASP file will be returned from the server .

(ASP stands for Active Server Pages. If you don't know how to write ASP, you can study it in our ASP Tutorial )


Getting XML from a Database

XML can be generated from a database without any installed XML software.

The XML response from the previous example can easily be modified to fetch its data from a database.

To generate an XML database response from the server, simply write the following code and save it as an ASP file:

```

response.ContentType = "text/xml"

set conn=Server.CreateObject("ADODB.Connection") 
conn.provider="Microsoft.Jet.OLEDB.4.0;"
conn.open server.mappath("/db/database.mdb")
sql="select fname,lname from tblGuestBook"
set rs=Conn.Execute(sql)


rs.MoveFirst()


response.write("&lt;?xml version='1.0' encoding='ISO-8859-1'?&gt;")
response.write("&lt;guestbook&gt;")
while (not rs.EOF)
  response.write("&lt;guest&gt;")
  response.write("&lt;fname&gt;" &amp;amp; rs("fname") &amp;amp; "&lt;/fname&gt;")
  response.write("&lt;lname&gt;" &amp;amp; rs("lname") &amp;amp; "&lt;/lname&gt;")
  response.write("&lt;/guest&gt;")
  rs.MoveNext()
wend


rs.close()
conn.close()
response.write("&lt;/guestbook&gt;")
  1  
  2---  
  3  
  4See the real life database output from this page  . 
  5
  6The example above uses ASP with ADO. If you don't know how to use ADO, you can study it in our  ADO tutorial  . 
  7
  8* * *
  9
 10#  XML Applications 
 11
 12![back](http://www.w3schools.com/images/btn_previous.gif) ![next](http://www.w3schools.com/images/btn_next.gif)
 13
 14* * *
 15
 16This chapter demonstrates a small framework for an XML application. 
 17
 18* * *
 19
 20##  Start with an XML document 
 21
 22**First we start with a simple XML document.**
 23
 24Take a look at our original demonstration document, the CD catalog. 
 25    
 26    
 27    <?xml version="1.0" encoding="ISO-8859-1"?>
 28<catalog>
 29<cd>
 30<title>Empire Burlesque</title>
 31<artist>Bob Dylan</artist>
 32<country>USA</country>
 33<company>Columbia</company>
 34<price>10.90</price>
 35<year>1985</year>
 36</cd>
 37    .
 38    .
 39    ... more ...
 40    .  
 41  
 42---  
 43  
 44If you have Internet Explorer 5.0 or higher,  see the full XML file  . 
 45
 46* * *
 47
 48##  Load the document into a Data Island 
 49
 50**A Data Island can be used to access the XML file.**
 51
 52To get your XML document "inside" an HTML page, add an XML Data Island to the page. 
 53    
 54    
 55    <xml async="false" id="xmldso" src="cd_catalog.xml">
 56</xml>  
 57  
 58---  
 59  
 60With the example code above, the XML file "cd_catalog.xml" will be loaded into an "invisible" Data Island called "xmldso". The async="false" attribute is added to the Data Island to make sure that all the XML data is loaded before any other HTML processing takes place. 
 61
 62* * *
 63
 64##  Bind the Data Island to an HTML Table 
 65
 66**An HTML table can be used to display the XML data.**
 67
 68To make your XML data visible on your HTML page, you must "bind" your XML Data Island to an HTML element. 
 69
 70To bind your XML data to an HTML table, add a data source attribute to the table, and add data field attributes to <span> elements inside the table data: 
 71    
 72    
 73    <table border="1" datasrc="#xmldso" width="100%">
 74<thead>
 75<th>Title</th>
 76<th>Artist</th>
 77<th>Year</th>
 78</thead>
 79<tr align="left">
 80<td><span datafld="TITLE"></span></td>
 81<td><span datafld="ARTIST"></span></td>
 82<td><span datafld="YEAR"></span></td>
 83</tr>
 84</table>  
 85  
 86---  
 87  
 88If you have Internet Explorer 5.0 or higher:  See how the XML data is displayed inside an HTML table  . 
 89
 90* * *
 91
 92##  Bind the Data Island to <span> or <div> elements 
 93
 94** <span> or <div> elements can be used to display XML data. **
 95
 96You don't have to use a table to display your XML data. Data from a Data Island can be displayed anywhere on an HTML page. 
 97
 98All you have to do is to add some <span> or <div> elements to your page. Use the data source attribute to bind the elements to the Data Island, and the data field attribute to bind each element to an XML element, like this: 
 99    
100    
101    <br/>Title:
102    <span datafld="TITLE" datasrc="#xmldso"></span>
103<br/>Artist:
104    <span datafld="ARTIST" datasrc="#xmldso"></span>
105<br/>Year:
106    <span datafld="YEAR" datasrc="#xmldso"></span>  
107  
108---  
109  
110or like this: 
111    
112    
113    <br/>Title:
114    <div datafld="TITLE" datasrc="#xmldso"></div>
115<br/>Artist:
116    <div datafld="ARTIST" datasrc="#xmldso"></div>
117<br/>Year:
118    <div datafld="YEAR" datasrc="#xmldso"></div>  
119  
120---  
121  
122If you have Internet Explorer 5.0 or higher:  See how the XML data is displayed inside the HTML elements  . 
123
124Note that if you use a <div> element, the data will be displayed on a new line. 
125
126With the examples above, you will only see one line of your XML data. To navigate to the next line of data, you have to add some scripting to your code. 
127
128* * *
129
130##  Add a Navigation Script to your XML 
131
132**Navigation has to be performed by a script.**
133
134To add navigation to the XML Data Island, create a script that calls the movenext() and moveprevious() methods of the Data Island. 
135    
136    
137    <script type="text/javascript">
138    function movenext()
139    {
140    x=xmldso.recordset
141    if (x.absoluteposition < x.recordcount)
142    	{
143    	x.movenext()
144    	}
145    }
146    function moveprevious()
147    {
148    x=xmldso.recordset
149    if (x.absoluteposition > 1)
150    	{
151    	x.moveprevious()
152    	}
153    }
154    </script>  
155  
156---  
157  
158If you have Internet Explorer 5.0 or higher:  See how you can navigate through the XML records  . 
159
160* * *
161
162##  All Together Now 
163
164**With a little creativity you can create a full application.**
165
166If you use what you have learned on this page, and a little imagination, you can easily develop this into a full application. 
167
168If you are running Internet Explorer 5.0 or higher:  See how you can add a little fancy to this application  . 
169
170* * *
171
172#  XML HTTP Requests 
173
174![back](http://www.w3schools.com/images/btn_previous.gif) ![next](http://www.w3schools.com/images/btn_next.gif)
175
176* * *
177
178If you are using IE 5.0 or higher, XML data can be requested from a server using an HTTP request. 
179
180* * *
181
182##  The Browser Request 
183
184**An HTTP request from the browser, can request XML from a server:**
185    
186    
187    var objHTTP = new ActiveXObject("Microsoft.XMLHTTP")
188    objHTTP.Open('GET','httprequest.asp',false)
189    objHTTP.Send()  
190  
191---  
192  
193To view the result from the request, you can display the result in your browser: 
194    
195    
196    document.all['A1'].innerText= objHTTP.status
197    document.all['A2'].innerText= objHTTP.statusText
198    document.all['A3'].innerText= objHTTP.responseText  
199  
200---  
201  
202Try it Yourself using JavaScript 
203
204Try it Yourself using VBScript 
205
206* * *
207
208##  Communicating with the Server 
209
210**With HTTP requests you can "communicate" with a server.**
211
212Communicating with a server using XML 
213
214In the example the response is "faked" on the server with this ASP code: 
215    
216    
217    ```
218
219    response.ContentType="text/xml"
220    txt="&lt;answer&gt;&lt;text&gt;12 Years&lt;/text&gt;&lt;/answer&gt;"
221    response.write(txt)
222    

So, the answer will always be 12 years, no matter what question is asked. In real life, you have to write some code to analyze the question and respond with a correct answer.


XML Behaviors - the new DHTML?

prev next


A behavior is a CSS attribute selector. It can point to an XML file that contains code to be executed against elements in a Web page.

Behaviors is not a W3C standard, but a Microsoft-only technology.


Behaviors - What are they?

A behavior is a new CSS attribute selector.

A behavior selector can point to a separate XML file that contains code to be executed against XML or HTML elements in a Web page.

Did you understand that? A method for completely removing script code from HTML pages? That's great! Now we can start writing script libraries, and attach our scripts to any element we want!


How does it work?

Take a look at this HTML file. It has a