XML Advanced-from w3schools.com

类别:.NET开发 点击:0 评论:0 推荐:
XML Namespaces

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:

<table> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table>

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

<table> <name>African Coffee Table</name> <width>80</width> <length>120</length> </table>

If these two XML documents were added together, there would be an element name conflict because both documents contain a <table> element with different content and definition.

Solving Name Conflicts using a Prefix

This XML document carries information in a table:

<h:table> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table>

This XML document carries information about a piece of furniture:

<f:table> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table>

Now the element name conflict is gone because the two documents use a different name for their <table> element (<h:table> and <f:table>).

By using a prefix, we have created two different types of <table> elements.

Using Namespaces

This XML document carries information in a table:

<h:table xmlns:h="http://www.w3.org/TR/html4/"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table>

This XML document carries information about a piece of furniture:

<f:table xmlns:f="http://www.w3schools.com/furniture"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table>

Instead 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.

The Namespace Attribute

The namespace attribute is placed in the start tag of an element and has the following syntax:


In the examples above, the namespace itself is defined using an Internet address:


The W3C namespace specification states that the namespace itself should be a Uniform Resource Identifier (URI).

When a namespace is defined in the start tag of an element, all child elements with the same prefix are associated with the same namespace.

Note 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.
Try to go to http://www.w3.org/TR/html4/.

Uniform Resource Identifiers

A 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.

Since our furniture example uses an internet address to identify its namespace, we can be sure that our namespace is unique.

Default Namespaces

Defining a default namespace for an element saves us from using prefixes in all the child elements. It has the following syntax:

<element xmlns="namespace">

This XML document carries information in a table:

<table xmlns="http://www.w3.org/TR/html4/"> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table>

This XML document carries information about a piece of furniture:

<table xmlns="http://www.w3schools.com/furniture"> <name>African Coffee Table</name> <width>80</width> <length>120</length> </table>
Namespaces in Real Use

When 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.

If 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":

<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/xsl"> <xsl:template match="/"> <html> <body> <table border="2" bgcolor="yellow"> <tr> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="CATALOG/CD"> <tr> <td><xsl:value-of select="TITLE"/></td> <td><xsl:value-of select="ARTIST"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

All text in an XML document will be parsed by the parser.

Only text inside a CDATA section is ignored by the parser.

Parsed Data

XML parsers normally parse all the text in an XML document.

When an XML element is parsed, the text between the XML tags is also parsed:

<message>This text is also parsed</message>

The 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):


and the parser will break it up into sub-elements like this:

<name> <first>Bill</first> <last>Gates</last> </name>
Escape Characters

Illegal XML characters have to be replaced by entity references.

If you place a character like "<" 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:

<message>if salary < 1000 then</message>

To avoid this, you have to replace the "<" character with an entity reference, like this:

<message>if salary &lt; 1000 then</message>

There are 5 predefined entity references in XML:

&lt; < less than &gt; > greater than &amp; & ampersand  &apos; ' apostrophe &quot; " quotation mark
Entity references always start with the "&" character and end with the ";" character.

Note: Only the characters "<" and "&" are strictly illegal in XML. Apostrophes, quotation marks and greater than signs are legal, but it is a good habit to replace them.


Everything inside a CDATA section is ignored by the parser.

If your text contains a lot of "<" or "&" characters - as program code often does - the XML element can be defined as a CDATA section.

A CDATA section starts with "<![CDATA[" and ends with "]]>":

<script> <![CDATA[ function matchwo(a,b) { if (a < b && a < 0) then { return 1 } else { return 0 } } ]]> </script>

In the previous example, everything inside the CDATA section is ignored by the parser.

Notes on CDATA sections:

A CDATA section cannot contain the string "]]>", therefore, nested CDATA sections are not allowed.

Also make sure there are no spaces or line breaks inside the "]]>" string.

XML Encoding

XML documents can contain foreign characters like Norwegian æøå, or French êèé.

To let your XML parser understand these characters, you should save your XML documents as Unicode.

Windows 95/98 Notepad

Windows 95/98 Notepad cannot save files in Unicode format. 

You can use Notepad to edit and save XML documents that contain foreign characters (like Norwegian or French æøå and êèé),

<?xml version="1.0"?> <note> <from>Jani</from> <to>Tove</to> <message>Norwegian: æøå. French: êèé</message> </note>

But if you save the file and open it with IE 5.0, you will get an ERROR MESSAGE.

Windows 95/98 Notepad with Encoding

Windows 95/98 Notepad files must be saved with an encoding attribute. 

To avoid this error you can add an encoding attribute to your XML declaration, but you cannot use Unicode.

The encoding below (open it with IE 5.0), will NOT give an error message:

<?xml version="1.0" encoding="windows-1252"?>

The encoding below (open it with IE 5.0), will NOT give an error message:

<?xml version="1.0" encoding="ISO-8859-1"?>

The encoding below (open it with IE 5.0), will NOT give an error message:

<?xml version="1.0" encoding="UTF-8"?>

The encoding below (open it with IE 5.0), WILL give an error message:

<?xml version="1.0" encoding="UTF-16"?>
Windows 2000 Notepad

Windows 2000 Notepad can save files as Unicode.

The 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):

<?xml version="1.0"?> <note> <from>Jani</from> <to>Tove</to> <message>Norwegian: æøå. French: êèé</message> </note>

The 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.

Windows 2000 Notepad with Encoding

Windows 2000 Notepad files saved as Unicode use "UTF-16" encoding.

If you add an encoding attribute to XML files saved as Unicode, windows encoding values will generate an error.

This encoding (open it), will NOT give an error message:

<?xml version="1.0" encoding="windows-1252"?>

This encoding (open it), will NOT give an error message:

<?xml version="1.0" encoding="ISO-8859-1"?>

This encoding (open it), will NOT give an error message:

<?xml version="1.0" encoding="UTF-8"?>

The 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.

<?xml version="1.0" encoding="UTF-16"?>
Error Messages

If you try to load an XML document into Internet Explorer 5, you can get two different errors indicating encoding problems:

An invalid character was found in text content.

You 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. 

Switch from current encoding to specified encoding not supported.

You 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.


The conclusion is that the encoding attribute has to specify the encoding used when the document was saved. My best advice to avoid errors is:

Use an editor that supports encoding. Make sure you know what encoding it uses. Use the same encoding attribute in your XML documents. A Simple XML Server

XML can be generated on a server without any installed XML controls.

Storing XML on the Server

XML files can be stored on your Internet server.

XML files can be stored on your Internet server, in exactly the same way as HTML files.

Start up your Notepad editor and write the following lines: 

<?xml version="1.0" encoding="ISO-8859-1"?> <note> <from>Jani</from> <to>Tove</to> <message>Remember me this weekend</message> </note>

All 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.

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.

Generating XML with ASP

XML can be generated on a server without any installed XML software.

To generate an XML response from your server - simply write the following code and save it as an ASP file on your web server :

<% response.ContentType="text/xml" response.Write("<?xml version='1.0' encoding='ISO-8859-1'?>") response.Write("<note>") response.Write("<from>Jani</from>") response.Write("<to>Tove</to>") response.Write("<message>Remember me this weekend</message>") response.Write("</note>") %>

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)


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

rs.close() conn.close() response.write("</guestbook>") %>

See the real life database output from this page.

The example above uses ASP with ADO. If you don't know how to use ADO, you can study it in our ADO tutorial.

XML Applications

This chapter demonstrates a small framework for an XML application.

Start with an XML document

First we start with a simple XML document.

Take a look at our original demonstration document, the CD catalog.

<?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> . . ... more ... .

If you have Internet Explorer 5.0 or higher, see the full XML file.

Load the document into a Data Island

A Data Island can be used to access the XML file.

To get your XML document "inside" an HTML page, add an XML Data Island to the page.

<xml src="cd_catalog.xml" id="xmldso" async="false"> </xml>

With 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.

Bind the Data Island to an HTML Table

An HTML table can be used to display the XML data.

To make your XML data visible on your HTML page, you must "bind" your XML Data Island to an HTML element.

To 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:

<table datasrc="#xmldso" width="100%" border="1"> <thead> <th>Title</th> <th>Artist</th> <th>Year</th> </thead> <tr align="left"> <td><span datafld="TITLE"></span></td> <td><span datafld="ARTIST"></span></td> <td><span datafld="YEAR"></span></td> </tr>


If you have Internet Explorer 5.0 or higher: See how the XML data is displayed inside an HTML table.

Bind the Data Island to <span> or <div> elements

<span> or <div> elements can be used to display XML data.

You 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.

All 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:

<br />Title: <span datasrc="#xmldso" datafld="TITLE"></span> <br />Artist: <span datasrc="#xmldso" datafld="ARTIST"></span> <br />Year: <span datasrc="#xmldso" datafld="YEAR"></span>

or like this:

<br />Title: <div datasrc="#xmldso" datafld="TITLE"></div> <br />Artist: <div datasrc="#xmldso" datafld="ARTIST"></div> <br />Year: <div datasrc="#xmldso" datafld="YEAR"></div>

If you have Internet Explorer 5.0 or higher: See how the XML data is displayed inside the HTML elements.

Note that if you use a <div> element, the data will be displayed on a new line.

With 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. 

Add a Navigation Script to your XML

Navigation has to be performed by a script.

To add navigation to the XML Data Island, create a script that calls the movenext() and moveprevious() methods of the Data Island.

<script type="text/javascript"> function movenext() { x=xmldso.recordset if (x.absoluteposition < x.recordcount) { x.movenext() } } function moveprevious() { x=xmldso.recordset if (x.absoluteposition > 1) { x.moveprevious() } } </script>

If you have Internet Explorer 5.0 or higher: See how you can navigate through the XML records.

All Together Now

With a little creativity you can create a full application.

If you use what you have learned on this page, and a little imagination, you can easily develop this into a full application.

If you are running Internet Explorer 5.0 or higher: See how you can add a little fancy to this application.

XML HTTP Requests

If you are using IE 5.0 or higher, XML data can be requested from a server using an HTTP request.

The Browser Request

An HTTP request from the browser, can request XML from a server:

var objHTTP = new ActiveXObject("Microsoft.XMLHTTP") objHTTP.Open('GET','httprequest.asp',false) objHTTP.Send()

To view the result from the request, you can display the result in your browser:

document.all['A1'].innerText= objHTTP.status document.all['A2'].innerText= objHTTP.statusText document.all['A3'].innerText= objHTTP.responseText

Try it Yourself using JavaScript

Try it Yourself using VBScript

Communicating with the Server

With HTTP requests you can "communicate" with a server.

Communicating with a server using XML

In the example the response is "faked" on the server with this ASP code:

<% response.ContentType="text/xml" txt="<answer><text>12 Years</text></answer>" response.write(txt) %>

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?

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 <style> element that defines a behavior for the <h1> element:

<html> <head> <style> h1 { behavior: url(behave.htc) } </style> </head> <body> <h1>Move your Mouse over me</h1> </body> </html>

Try it yourself with this example, and move the mouse over the text.

The behavior code is stored in an XML document behave.htc as shown below:

<component> <attach for="element" event="onmouseover" handler="hig_lite" /> <attach for="element" event="onmouseout" handler="low_lite" /> <script type="text/javascript"> function hig_lite() { element.style.color=255 } function low_lite() { element.style.color=0 } </script> </component>

The behavior file contains JavaScript. The script is wrapped in a <component> element. The component wrapper also contains the event handlers for the script. Nice behavior, isn't it?

XML Related Technologies

This chapter contains a list of technologies that are important to the understanding and development of XML applications.

It can also be viewed as "where to go from here" information, if you want to study more XML.

XHTML - Extensible HTML

XHTML is the re-formulation of HTML 4.01 in XML. XHTML 1.0 is the latest version of HTML. Read more in our XHTML tutorial.

CSS - Cascading Style Sheets

CSS style sheets can be added to XML documents to provide display information. Read more in our CSS tutorial.

XSL - Extensible Style Sheet Language

XSL consists of three parts: XML Document Transformation (renamed XSLT, see below), a pattern matching syntax (renamed XPath, see below), and a formatting object interpretation. 

XSLT - XML Transformation

XSLT is far more powerful than CSS. It can be used to transform XML files into many different output formats. Read more in our XSLT tutorial.

XPath - XML Pattern Matching

XPath is a language for addressing parts of an XML document. XPath was designed to be used by both XSLT and XPointer.

XLink - XML Linking Language

The XML Linking Language (XLink) allows elements to be inserted into XML documents in order to create links between XML resources.

XPointer - XML Pointer Language

The XML Pointer Language (XPointer) supports addressing into the internal structures of XML documents, such as elements, attributes, and content.

DTD - Document Type Definition

A DTD can be used to define the legal building blocks of an XML document. Read more in our DTD tutorial.


XML namespaces defines a method for defining element and attribute names used in XML by associating them with URI references.

XSD - XML Schema

Schemas are powerful alternatives to DTDs. Schemas are written in XML, and support namespaces and data types. Read more in our Schema tutorial.

XDR - XML Data Reduced

XDR is a reduced version of XML Schema. Support for XDR was shipped with  Internet Explorer 5.0 when XML Schema was still a working draft. Microsoft has committed full support for XML Schema as soon as the specification becomes a W3C Recommendation.

DOM - Document Object Model

The DOM defines interfaces, properties and methods to manipulate XML documents. Read more in our DOM tutorial.

XQL - XML Query Language

The XML Query Language supports query facilities to extract data from XML documents.

SAX - Simple API for XML

SAX is another interface to read and manipulate XML documents.

W3C Recommendations

The World Wide Web Consortium (W3C) was founded in 1994 to lead the Web by developing common WWW protocols like HTML, CSS and XML.

The most important work done by the W3C is the development of Web specifications (called "Recommendations") that describe communication protocols (like HTML and XML) and other building blocks of the Web.

Read more about the status of each XML standard at our W3C School.

XML Editors

If you are serious about XML, you will benefit from of using a professional XML Editor.

XML is Text Based

XML is a text based markup language.

One great thing about XML is that XML files can be created and edited using a simple text editor like Notepad.

However, when you start working with XML, you will soon find that it is better to edit XML documents using a professional XML editor.

Why Not Notepad?

Many "hardcore" web developers use Notepad to edit both HTML and XML documents because Notepad is free and simple to use, and personally I often use Notepad for quick editing of simple HTML, CSS, and XML files.

But, if you use Notepad for XML editing, you will soon run into problems.

Notepad does not know that you are writing XML, so it will not be able to assist you. You will create many errors, and as your XML documents grow larger you will lose control.

Why an XML Editor?

Today XML is an important technology, and everyday we can see XML playing a more and more critical role in new web development.

New development projects use XML based technologies like:

XML Schema to define XML structures and data types XSLT to transform XML data SOAP to exchange XML data between applications WSDL to describe web services RDF to describe web resources XPath and XQuery to access XML data SMIL to define graphics... and much more

To be able to write XML documents for all your new development projects, you will need an intelligent editor to help you write error free XML documents.

XML Editors

Good XML editors will help you to write error free XML documents, validate your text against a DTD or a schema, and force you to stick to a valid XML structure.

A good XML editor should be able to:

Add closing tags to your opening tags automatically Force you to write valid XML Verify your XML against a DTD Verify your XML against a Schema Color code your XML syntax XMLSPY

At W3Schools we have been using XMLSPY for many years. XMLSPY is our favorite XML editor. These are some of the features we specially like:

Easy to use Syntax coloring Automatic tag completion Automatic well-formed check Easy switching between text view and grid view Built in DTD and / or Schema validation Built in graphical XML Schema designer Powerful conversion utilities Database import and export Built in templates for most XML document types Built in XPath analyzer Full SOAP and WSDL capabilities Powerful project management

Read more about XMLSPY