text: This action might not be possible to undo. Are you sure you want to continue?
  XML is important to know, and very easy to learn. Start learning XML now!
  XML Document Example
  <?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>:
  <note> 
  XML became a W3C Recommendation February 10, 1998. To read more about the XML activities at W3C, please read our W3C Tutorial.
  XML is Everywhere
  XML is now as important for the Web as HTML was to the foundation of the Web. XML is the most common tool for data transmissions between all sorts of applications.
  XML is used in many aspects of web development, often to simplify data storage and sharing.
  without losing data. With a few lines of JavaScript code. is always time consuming. XML Simplifies Platform Changes Upgrading to new systems (hardware or software platforms). since the data can be read by different incompatible applications. This way you can concentrate on using HTML for layout and display. Exchanging data as XML greatly reduces this complexity. XML data is stored in plain text format. new applications. This makes it much easier to create data that can be shared by different applications. XML data is stored in text format. XML Simplifies Data Transport One of the most time-consuming challenges for developers is to exchange data between incompatible systems over the Internet. it will take a lot of work to edit the HTML each time the data changes. you can read an external XML file and update the data content of your web page.and hardware-independent way of storing data. . computer systems and databases contain data in incompatible formats. data can be stored in separate XML files. or new browsers.XML Separates Data from HTML If you need to display dynamic data in your HTML document. This provides a software. Large amounts of data must be converted and incompatible data is often lost. and be sure that changes in the underlying data will not require any changes to the HTML. This makes it easier to expand or upgrade to new operating systems. With XML. XML Simplifies Data Sharing In the real world.
  news feeds. voice machines. or people with other disabilities. The future might give us word processors. An Example XML Document XML documents use a self-describing and simple syntax: . etc).XML Makes Your Data More Available Different applications can access your data. not only in HTML pages. spreadsheet applications and databases that can read each other's data in XML format. without any conversion utilities in between.. your data can be available to all kinds of "reading machines" (Handheld computers. and make it more available for blind people. XML is Used to Create New Internet Languages A lot of new Internet languages are created with XML. but also from XML data sources. XML documents form a tree structure that starts at "the root" and branches to "the leaves".
  0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The first line is the XML declaration. from.<?xml version="1. from this example. that the XML document contains a note to Tove from Jani. The tree starts at the root and branches to the lowest level of the tree. The elements in an XML document form a document tree. The next line describes the root element of the document (like saying: "this document is a note"): <note> The next 4 lines describe 4 child elements of the root (to.0) and the encoding used (ISO-8859-1 = Latin-1/West European character set). All elements can have sub elements (child elements): . heading. and body): <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> And finally the last line defines the end of the root element: </note> You can assume. Don't you agree that XML is pretty self-descriptive? XML Documents Form a Tree Structure XML documents must contain a root element. This element is "the parent" of all other elements. It defines the XML version (1.
  Parent elements have children.. and sibling are used to describe the relationships between elements.</subchild> </child> </root> The terms parent. Children on the same level are called siblings (brothers or sisters).<root> <child> <subchild>. Rowling</author> . child... Example: The image above represents one book in the XML below: <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30..00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. All elements can have text content and attributes (just like in HTML).
  it is illegal to omit the closing tag.95</price> </book> </bookstore> The root element in the example is <bookstore>.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. <price>. Ray</author> <year>2003</year> <price>39.<year>2005</year> <price>29. All elements must have a closing tag: <p>This is a paragraph</p> <p>This is another paragraph</p> Note: You might have noticed from the previous example that the XML declaration did not have a closing tag. The declaration is not a part of the XML document itself. The <book> element has 4 children: <title>. <year>. and easy to use. The syntax rules of XML are very simple and logical. .< author>. All <book> elements in the document are contained within <bookstore>. The rules are easy to learn. and it has no closing tag. All XML Elements Must Have a Closing Tag In HTML. some elements do not have to have a closing tag: <p>This is a paragraph <p>This is another paragraph In XML. This is not an error.
  <root> <child> <subchild>. XML Elements Must be Properly Nested In HTML. XML Documents Must Have a Root Element XML documents must contain one element that is the parent of all other elements. This element is called the root element. The tag <Letter> is different from the tag <letter>. "Properly nested" simply means that since the <i> element is opened inside the <b> element. Use whatever you prefer.. all elements must be properly nested within each other: <b><i>This text is bold and italic</i></b> In the example above.. Opening and closing tags must be written with the same case: <Message>This is incorrect</message> <message>This is correct</message> Note: "Opening and closing tags" are often referred to as "Start and end tags".</subchild> </child> </root> .. it must be closed inside the <b> element..XML Tags are Case Sensitive XML tags are case sensitive. you might see improperly nested elements: <b><i>This text is bold and italic</b></i> In XML. It is exactly the same thing.
  1000 then</message> There are 5 predefined entity references in XML: . Entity References Some characters have a special meaning in XML. This will generate an XML error: <message>if salary < 1000 then</message> To avoid this error. replace the "<" character with an entity reference: <message>if salary <. it will generate an error because the parser interprets it as the start of a new element. The first one is incorrect.XML Attribute Values Must be Quoted XML elements can have attributes in name/value pairs just like in HTML. If you place a character like "<" inside an XML element.. Study the two XML documents below. the attribute values must always be quoted. In XML.
  This is a comment --> White-space is Preserved in XML HTML truncates multiple white-space characters to one single white-space: HTML: Output: Hello Hello Tove Tove With XML. &.<. . The greater than character is legal. >. Macintosh applications also use an LF to store a new line. ". a new line is normally stored as an LF character. XML Stores New Line as LF In Windows applications. XML stores a new line as LF. but it is a good habit to replace it. <!-. &apos. a new line is normally stored as a pair of characters: carriage return (CR) and line feed (LF). < > & ' " less than greater than ampersand apostrophe quotation mark Note: Only the characters "<" and "&" are strictly illegal in XML. Comments in XML The syntax for writing comments in XML is similar to that of HTML. In Unix applications. the white-space in a document is not truncated.
  Rowling</author> <year>2005</year> <price>29. <bookstore> <book category="CHILDREN"> <title>Harry Potter</title> <author>J K. An element can contain: other elements text attributes or a mix of all of the above. and <price> have text content because they contain text. <year>.99</price> </book> <book category="WEB"> <title>Learning XML</title> <author>Erik T.. <book> also has an attribute (category="CHILDREN"). etc) Names cannot contain spaces . XML Naming Rules XML elements must follow these naming rules: Names can contain letters. Ray</author> <year>2003</year> <price>39. or Xml. because they contain other elements. and other characters Names cannot start with a number or punctuation character Names cannot start with the letters xml (or XML. <title>. <bookstore> and <book> have element contents.. numbers. <author>.95</price> </book> </bookstore> In the example above. What is an XML Element? An XML element is everything from (including) the element's start tag to (including) the element's end tag.An XML document contains XML Elements.
  like this: <book_title> not like this: <the_title_of_the_book>." Avoid ":" characters. but watch out for problems if your software vendor doesn't support them. Avoid "-" characters. Look at the following XML example: <note> <to>Tove</to> <from>Jani</from> <body>Don't forget me this weekend!</body> </note> Let's imagine that we created an application that extracted the <to>. XML Elements are Extensible XML elements can be extended to carry more information. <from>. If you name something "first-name. A good practice is to use the naming rules of your database for the elements in the XML documents. Names should be short and simple. Best Naming Practices Make names descriptive. If you name something "first. no words are reserved. Non-English letters like éòá are perfectly legal in XML. Names with an underscore separator are nice: <first_name>." some software may think that "name" is a property of the object "first. Colons are reserved to be used for something called namespaces (more later). XML documents often have a corresponding database." some software may think you want to subtract name from first. <last_name>.name.Any name can be used. and <body> elements from the XML document to produce this output: MESSAGE . Avoid "." characters.
  The application should still be able to find the <to>.asp"> Attributes often provide information that is not a part of the data.gif</file> . and <body> elements in the XML document and produce the same output.gif"> <a href="demo. XML elements can have attributes. Attributes provide additional information about an element. <from>. One of the beauties of XML. In the example below. but can be important to the software that wants to manipulate the element: <file type="gif">computer. the file type is irrelevant to the data. attributes provide additional information about elements: <img src="computer. XML Attributes In HTML. is that it can be extended without breaking applications. just like HTML.To: Tove From: Jani Don't forget me this weekend! Imagine that the author of the XML document added some extra information to it: <note> <date>2008-01-10</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Should the application break or crash? No.
  In the last. Both examples provide the same information. Use elements instead. Attributes Take a look at these examples: <person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> <person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> In the first example sex is an attribute. For a person's sex. like in this example: <gangster name='George "Shotgun" Ziegler'> or you can use character entities: <gangster name="George ". Ziegler"> XML Elements vs.Shotgun". Either single or double quotes can be used. Attributes are handy in HTML. the person element can be written like this: <person sex="female"> or like this: <person sex='female'> If the attribute value itself contains double quotes you can use single quotes.XML Attributes Must be Quoted Attribute values must always be quoted. sex is an element. There are no rules about when to use attributes or when to use elements. . In XML my advice is to avoid them.: attributes cannot contain multiple values (elements can) attributes cannot contain tree structures (elements can) . attributes above are for identifying the different notes. These IDs can be used to identify XML elements in much the same way as the id attribute in HTML. What I'm trying to say here is that metadata (data about data) should be stored as attributes. Use attributes for information that is not relevant to the data. XML with correct syntax is "Well Formed" XML. attributes are not easily expandable (for future changes) Attributes are difficult to read and maintain. Use elements for data. XML validated against a DTD is "Valid" XML. Don't end up like this: <note day="10" month="01" year="2008" to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"> </note> XML Attributes for Metadata Sometimes ID references are assigned to elements. . and the data itself should be stored as elements. It is not a part of the note itself.
  which also conforms to the rules of a Document Type Definition (DTD): <?xml version="1.Well Formed XML Documents A "Well Formed" XML document has correct XML syntax. is a reference to an external DTD file. XML DTD The purpose of a DTD is to define the structure of an XML document. The content of the file is shown in the paragraph below. It defines the structure with a list of legal elements: .0" encoding="ISO-8859-1"?> <!DOCTYPE note SYSTEM "Note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The DOCTYPE declaration in the example above. The syntax rules were described in the previous chapters: XML documents must have a root element XML elements must have a closing tag XML tags are case sensitive XML elements must be properly nested XML attribute values must be quoted <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Valid XML Documents A "Valid" XML document is a "Well Formed" XML document.
  <!DOCTYPE note [ <!ELEMENT note (to. called XML Schema: > If you want to study XML Schema. we have created an XML validator to syntaxcheck your XML.body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> If you want to study DTD. XML Schema W3C supports an XML-based alternative to DTD. you will find our DTD tutorial on our homepage. Please see the next chapter. A General XML Validator To help you check the syntax of your XML files. Use our XML validator to syntax-check your XML. you will find our Schema tutorial on our homepage.heading.from. .
  Syntax-Check an XML File You can syntax-check an XML file by typing the URL of the file into the input field below. The file "note_error. . errors are not allowed. If you want see an error free message. we have created an XML validator. and syntax-check it by clicking the "Validate" button. see the last paragraph on this page. Syntax-Check Your XML To help you syntax-check your XML. it's because your browser security does not allow file access across domains. With XML.XML Errors Will Stop You Errors in XML documents will stop your XML applications. substitute the "note_error. fast. Note: This only checks if your XML is "Well formed". The W3C XML specification states that a program should stop processing an XML document if it finds an error.xml" demonstrates your browsers error handling. The reason is that XML software should be small. HTML browsers are big and incompatible because they have a lot of unnecessary code to deal with (and display) HTML errors.xml". If you want to validate your XML against a DTD. and compatible.xml" with "cd_catalog. Paste your XML into the text area below. HTML browsers will display documents with errors (like missing end tags). and then click the "Validate" button: Filename: Note: If you get an "Access denied" error.
  select "View Page Source" or "View Source" from the browser menu. Netscape. Mozilla. To view the raw XML. Viewing XML Files <?xml version="1.0" encoding="ISO-8859-1"?> . Note: In Chrome. Raw XML files can be viewed in all major browsers. you must right click the page and select "View Source" . To view the raw XML source (without the + and . you can validate your XML in the text area below.signs). only the element text will be displayed. Firefox. and Opera will not. and Safari.xml The XML document will be displayed with color-coded root and child elements. Don't expect XML files to be displayed as HTML pages. A plus (+) or minus sign (-) to the left of the elements can be clicked to expand or collapse the element structure.Validate Your XML Against a DTD If you know DTD.<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Look at this XML file: note. Just add the DOCTYPE declaration to your XML and click the "Validate" button: Note: Only Internet Explorer will actually check your XML against the DTD. Opera.
  With CSS (Cascading Style Sheets) you can add display information to an XML document.Viewing an Invalid XML File If an erroneous XML file is opened. the browser will report the error. XSLT and JavaScript. An XML plant catalog This is a plant catalog from a plant shop. Without any information about how to display the data. In the next chapters. using CSS. stored as XML data. An XML CD catalog This is a CD collection. Displaying your XML Files with CSS? . Since XML tags are "invented" by the author of the XML document. most browsers will just display the XML document as it is. Look at this XML file: note_error. A Simple Food Menu This is a breakfast food menu from a restaurant. Why Does XML Display Like This? XML documents do not carry information about how to display the data. stored as XML data. we will take a look at different solutions to the display problem.xml Other XML Examples Viewing some XML documents will help you get the XML feeling. browsers do not know if a tag like <table> describes an HTML table or a dining table. stored as XML data.
  W3C recommends using XSLT instead.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/css" href="cd_catalog.css"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10. Below is an example of how to use a CSS style sheet to format an XML document: Take a look at this XML file: The CD catalog Then look at this style sheet: The CSS file Finally. . The second line links the XML file to the CSS file: <?xml version="1. view: The CD catalog formatted with the CSS file Below is a fraction of the XML file. </CATALOG> Formatting XML with CSS is not the most common method. .It is possible to use CSS to format an XML document.90</PRICE> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <COMPANY>CBS Records</COMPANY> <PRICE>9. .90</PRICE> <YEAR>1988</YEAR> </CD> . See the next chapter.
  before it is displayed by a browser: Display XML with XSLT If you want to learn more about XSLT. View the result.With XSLT you can transform an XML document into HTML. study our XML DOM tutorial. XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS. XMLHttpRequest Example . Different browsers may produce different result when transforming XML with XSLT. The XMLHttpRequest Object The XMLHttpRequest object is used to exchange data with a server behind the scenes. To reduce this problem the XSLT transformation can be done on the server. Transforming XML with XSLT on the Server In the example above. Displaying XML with XSLT XSLT is the recommended style sheet language of XML. when the browser reads the XML file. the XSLT transformation is done by the browser. find our XSLT tutorial on our homepage. XSLT can be used to transform XML into HTML..
  In the next chapter. Syntax for creating an XMLHttpRequest object: xmlhttp=new XMLHttpRequest().which can then be manipulated with a JavaScript. Chrome. All modern browsers have a built-in XML parser.XMLHttpRequest) {// code for IE7+. Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object: xmlhttp=new ActiveXObject("Microsoft. Parse an XML Document The following code fragment parses an XML document into an XML DOM object: if (window. } . Safari. we will use the XMLHttpRequest object to retrieve XML information from a server. Firefox. and Opera) have a built-in XMLHttpRequest object.XMLHTTP"). an XMLHttpRequest is sent to the server and name suggestions are returned (from a file on the server): Type a letter in the input box: First Name Suggestions: Create an XMLHttpRequest Object All modern browsers (IE7+. Chrome. Firefox. An XML parser converts an XML document into an XML DOM object . Opera.When you type a character in the input field below. Safari xmlhttp=new XMLHttpRequest().
  .xml". txt=txt+"<title>Everyday Italian</title>".open("GET". txt=txt+"<year>2005</year>". modern browsers do not allow access across domains.send(). txt=txt+"</book></bookstore>". xmlDoc=parser.responseXML. xmlDoc. } Note: Internet Explorer uses the loadXML() method to parse an XML string. xmlhttp.async="false".parseFromString(txt. if (window.DOMParser) { parser=new DOMParser(). IE5 xmlhttp=new ActiveXObject("Microsoft."text/xml").XMLHTTP").XMLDOM"). xmlDoc. txt=txt+"<author>Giada De Laurentiis</author>". } xmlhttp. while other browsers use the DOMParser object. Access Across Domains For security reasons. xmlDoc=xmlhttp.loadXML(txt)."books. } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft. Parse an XML String The following code fragment parses an XML string into an XML DOM object: txt="<bookstore><book>".false).else {// code for IE6.
  xml") into an XML DOM object and then extracts some info from it with a JavaScript: . The HTML DOM The HTML DOM defines a standard way for accessing and manipulating HTML documents.This means. The XML DOM views an XML document as a tree-structure. The XML DOM In the next chapter you will learn how to access and retrieve data from the XML DOM object. The elements. must be located on the same server. All elements can be accessed through the DOM tree. that both the web page and the XML file it tries to load. You can learn more about the XML DOM in our XML DOM tutorial. Load an XML File . and their attributes are all known as nodes.Cross-browser Example The following example parses an XML document ("note. Their content (text and attributes) can be modified or deleted. A DOM (Document Object Model) defines a standard way for accessing and manipulating documents. and new elements can be created. All HTML elements can be accessed through the HTML DOM. You can learn more about the HTML DOM in our HTML DOM tutorial. their text. The XML DOM The XML DOM defines a standard way for accessing and manipulating XML documents.
  Chrome. document.nodeValue.innerHTML= xmlDoc.getElementsByTagName("body")[0].childNodes[0].responseXML. document.Example <html> <body> <h1>W3Schools Internal Note</h1> <div> <b>To:</b> <span id="to"></span><br /> <b>From:</b> <span id="from"></span><br /> <b>Message:</b> <span id="message"></span> </div> <script type="text/javascript"> if (window. </script> </body> </html> Try it yourself » . } xmlhttp.childNodes[0].getElementsByTagName("from")[0].XMLHttpRequest) {// code for IE7+. } else {// code for IE6. xmlhttp.innerHTML= xmlDoc.nodeValue. Opera.false).innerHTML= xmlDoc. IE5 xmlhttp=new ActiveXObject("Microsoft. Safari xmlhttp=new XMLHttpRequest().getElementById("from").send().getElementById("message").getElementById("to"). document."note.XMLHTTP").getElementsByTagName("to")[0].nodeValue. Firefox.xml". xmlDoc=xmlhttp.open("GET".childNodes[0].
  if (window.nodeValue Notice that even if the XML file contains only ONE <to> element you still have to specify the array index [0].DOMParser) { parser=new DOMParser().childNodes[0]. xmlDoc=parser. Load an XML String . txt=txt+"<from>Jani</from>".Important Note! To extract the text "Tove" from the <to> element in the XML file above ("note. } ."text/xml"). txt=txt+"<body>Don't forget me this weekend!</body>". txt=txt+"<heading>Reminder</heading>". txt=txt+"</note>". txt=txt+"<to>Tove</to>". the syntax is: getElementsByTagName("to")[0].Cross-browser Example The following example parses an XML string into an XML DOM object and then extracts some info from it with a JavaScript: Example <html> <body> <h1>W3Schools Internal Note</h1> <div> <b>To:</b> <span id="to"></span><br /> <b>From:</b> <span id="from"></span><br /> <b>Message:</b> <span id="message"></span> </div> <script> txt="<note>". This is because the getElementsByTagName() method returns an array.parseFromString(txt.xml").
  loadXML(txt). we loop through an XML file ("cd_catalog.send().childNodes[0]. Safari xmlhttp=new XMLHttpRequest().XMLHTTP").innerHTML= xmlDoc.xml".xml"). xmlhttp.innerHTML= xmlDoc.XMLDOM").nodeValue. document. if (window. IE5 xmlhttp=new ActiveXObject("Microsoft.
  for (i=0.write(x[i].getElementsByTagName("ARTIST")[0].write("</td></tr>").xml" file. document. document.write("<table border='1'>").xmlDoc=xmlhttp.nodeValue).getElementsByTagName("CD").i<x. visit our XML DOM tutorial.nodeValue).childNodes[0].responseXML.length.write(x[i]. HTML. } document.childNodes[0]. </script> </body> </html> Try it yourself » For more information about using JavaScript and the XML DOM.write("<tr><td>"). document.write("</table>"). XML DOM and JavaScript. var x=xmlDoc.i++) { document.write("</td><td>"). Display the First CD in an HTML div Element . document. document.getElementsByTagName("TITLE")[0]. The XML Document Used In this application we will use the "cd_catalog. XML Applications « Previous Next Chapter » This chapter demonstrates some small XML applications built on XML.
  unless you are on the last CD if (i<x. i=0.nodeValue). displayCD().length-1) { i++.getElementsByTagName("ARTIST")[0].childNodes[0].The following example gets the XML data from the first CD element and displays it in an HTML element with id="showCD". title=(x[i].nodeValue). txt="Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year. } } function previous() { // displays the previous CD.getElementsByTagName("YEAR")[0].getElementsByTagName("TITLE")[0].childNodes[0].innerHTML=txt.nodeValue). unless you are on the first CD if (i>0) . function displayCD() { artist=(x[i]. } Try it yourself » Navigate Between the CDs To navigate between the CDs in the example above. document. The displayCD() function is called when the page is loaded: Example x=xmlDoc.getElementsByTagName("CD").childNodes[0].getElementById("showCD"). year=(x[i]. add a next() and previous() function: Example function next() { // display the next CD.
  { i--. visit our XML DOM tutorial. XML Namespaces provide a method to avoid element name conflicts. element names are defined by the developer. displayCD(). For more information about using JavaScript and the XML DOM. This XML carries HTML table information: <table> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table> This XML carries information about a table (a piece of furniture): <table> <name>African Coffee Table</name> . } } Try it yourself » Show Album Information When Clicking On a CD The last example shows how you can show album information when the user clicks on a CD: Try it yourself. Name Conflicts In XML. This often results in a conflict when trying to mix XML documents from different XML applications.
  <width>80</width> <length>120</length> </table> If these XML fragments were added together. and a piece of furniture: <h:table> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> In the example above. xmlns:prefix="URI". there would be a name conflict. The namespace declaration has the following syntax. but the elements have different content and meaning. Solving the Name Conflict Using a Prefix Name conflicts in XML can easily be avoided using a name prefix. a so-called namespace for the prefix must be defined. XML Namespaces .The xmlns Attribute When using prefixes in XML. there will be no conflict because the two <table> elements have different names. Both contain a <table> element. The namespace is defined by the xmlns attribute in the start tag of an element. This XML carries information about an HTML table. An XML parser will not know how to handle these differences. .
  w3schools. Namespaces can be declared in the elements where they are used or in the XML root element: <root xmlns: <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root> In the example above.w3. When a namespace is defined for an element. the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified namespace.w3. all child elements with the same prefix are associated with the same namespace.com/furniture"> <h:table> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> .<root> <h:table xmlns: <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f=".
  w3schools.org/TR/html4/"> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table> This XML carries information about a piece of furniture: <table xmlns=". Try to go to. Another. It has the following syntax: .
  w3. you can see that most of the tags are HTML tags. identified by the namespace xmlns: <xsl:template <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr> > If you want to learn more about XSLT. When an XML element is parsed. Characters like "<" and "&" are illegal in XML elements.Parsed Character Data XML parsers normally parse all the text in an XML document. .(Unparsed) Character Data The term CDATA is used about text data that should not be parsed by the XML parser. PCDATA . CDATA . But text inside a CDATA section will be ignored by the parser. as in this example. 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. please find our XSLT tutorial at our homepage.. All text in an XML document will be parsed by the parser.
  "<" "]]>":
  <script> <!.
  XML Encoding
  « Previous Next Chapter » double-byte Unicode (UTF-byte encoding it will. The following encoding (open it), will give an error message:
  <?xml version="1.0" encoding="windows-1252"?>
  The following encoding (open it), will give an error message:
  <?xml version="1.0" encoding="ISO-8859-1"?>
  The following encoding (open it), will give an error message:
  <?xml version="1.0" encoding="UTF-8"?>
  The following encoding (open it), will NOT give an error:
  <?xml version="1.0" encoding="UTF-16"?>
  Conclusion
  Always use the encoding attribute Use an editor that supports encoding Make sure you know what encoding the editor uses Use the same encoding in your encoding attribute
  XML on the Server
  « Previous Next Chapter »
  XML files are plain text files just like HTML files. XML can easily be stored and generated by a standard web server.
  Storing XML Files on the Server
  Write("<message>Remember me this weekend</message>") response. See how the ASP file will be returned from the server.XML files can be stored on an Internet server exactly the same way as HTML files.simply write the following code and save it as an ASP file on the web server: <% response. Generating XML with ASP XML can be generated on a server without any installed XML software.ContentType="text/xml" response.Write("<to>Tove</to>") response.0' encoding='ISO-8859-1'?>") response. you will find our ASP tutorial on our homepage.Write("<?xml version='1.0" encoding="ISO-8859-1"?> <note> <from>Jani</from> <to>Tove</to> <message>Remember me this weekend</message> </note> Save the file on your web server with a proper name like "note. Start Windows Notepad and write the following lines: <?xml version="1.xml". If you want to study ASP.Write("<from>Jani</from>") response.Write("</note>") %> Note that the content type of the response must be set to "text/xml".Write("<note>") response. To generate an XML response from the server . Generating XML with PHP .
  open server. ?> Note that the content type of the response header must be set to "text/xml".write("<?xml version='1.mdb") sql="select fname.lname from tblGuestBook" set rs=Conn. echo "<to>Tove</to>". simply write the following code and save it as an ASP file on the web server: <% response. See how the PHP file will be returned from the server.CreateObject("ADODB. If you want to study PHP.write("<guestbook>") while (not rs. echo "<note>". echo "<message>Remember me this weekend</message>". use following code: <?php header("Content-type: text/xml").0' encoding='ISO-8859-1'?>".Execute(sql) response.0' encoding='ISO-8859-1'?>") response.write("<lname>" & rs("lname") & "</lname>") . echo "<from>Jani</from>".EOF) response.write("<guest>") response. echo "<?xml version='1. you will find our PHP tutorial on our homepage.OLEDB. To generate an XML database response from the server. Generating XML From a Database XML can be generated from a database without any installed XML software.write("<fname>" & rs("fname") & "</fname>") response.Jet.provider="Microsoft. echo "</note>".mappath("/db/database.To generate an XML response from the server using PHP.ContentType = "text/xml" set conn=Server.0.4." conn.Connection") conn.
  load(Server. If you want to study ASP and ADO.CreateObject("Microsoft.close() response. and loads the XML file into memory.close() conn.async = false xml.xsl")) 'Transform file Response.write("</guestbook>") %> See the real life database output from the ASP file above. .Write(xml. Transforming XML with XSLT on the Server This ASP transforms an XML file to XHTML on the server: <% 'Load XML set xml = Server. you will find the tutorials on our homepage.XMLDOM") xml.async = false xsl. The second block of code creates another instance of the parser and loads the XSL file into memory.response.CreateObject("Microsoft.write("</guest>") rs.xml")) 'Load XSL set xsl = Server.XMLDOM") xsl. The example above uses ASP with ADO.MapPath("simple.MoveNext() wend rs.transformNode(xsl)) %> Example explained The first block of code creates an instance of the Microsoft XML parser (XMLDOM).load(Server.MapPath("simple.
  and sends the result as XHTML to your browser.XMLDOM") xmlDoc. Nice! See how it works. .Save("test.CreateObject("Microsoft.Advanced In an earlier chapter of this tutorial we introduced the XML DOM.xml") %> XML DOM Advanced « Previous Next Chapter » The XML DOM . In this chapter we will explain some other important XML DOM methods.. The last line of code transforms the XML document using the XSL document.async="false" xmlDoc. and we used the getElementsByTagName() method to retrieve data from an XML document. You can learn more about the XML DOM in our XML DOM tutorial.loadXML(text) xmlDoc.
  Get the Value of an Element The XML file used in the examples below: books.nodeValue.getElementsByTagName("title")[0]. The following example retrieves the text value of the first <title> element: Example txt=xmlDoc.childNodes[0].getElementsByTagName("title")[0]. Try it yourself » Get the Value of an Attribute The following example retrieves the text value of the "lang" attribute of the first <title> element: Example txt=xmlDoc. x.nodeValue="Easy Cooking".getElementsByTagName("title")[0]. Try it yourself » Change the Value of an Element The following example changes the text value of the first <title> element: Example x=xmlDoc.childNodes[0].xml. Try it yourself » .getAttribute("lang").
  and then append it to an existing node.setAttribute("edition". it is necessary to both create a new element node and a new text node. and adds it to the first <book> element: Example newel=xmlDoc. The XML DOM appendChild() method adds a child node to a node (after the last child). for(i=0. The following example adds a new attribute (edition="first") to each <book> element: Example x=xmlDoc.getElementsByTagName("book").Create a New Attribute The XML DOM setAttribute() method can be used to change the value of an existing attribute. .i<x. To create a new element with text content. The XML DOM createTextNode() method creates a new text node."first"). The following example creates a new element (<edition>). or to create a new attribute.createElement("edition"). with the following text: First.i++) { x[i]. } Try it yourself » Create an Element The XML DOM createElement() method creates a new element node.length.
  getElementsByTagName("book")[0].getElementsByTagName("book"). Internet Explorer . x=xmlDoc. x. x[0].newtext=xmlDoc.childNodes[0]).appendChild(newtext). Firefox treats new lines as empty text nodes. Internet Explorer does not.createTextNode("First").removeChild(x. . Try it yourself » Note: The result of the example above may be different depending on what browser you use. Here are some technologies you should try to avoid when using XML.appendChild(newel).XML Data Islands What is it? An XML data island is XML data embedded into an HTML page. Try it yourself » Example explained: Create an <edition> element Create a text node with the following text: First Append the text node to the new <edition> element Append the <edition> element to the first <book> element Remove an Element The following example removes the first node in the first <book> element: Example x=xmlDoc. newel. You can read more about this and how to avoid it in our XML DOM tutorial.
  For more information about JavaScript and XML DOM. and the src attribute points to the XML file: Example This example only works in IE <html> <body> <xml id="cdcat" src="cd_catalog. .Why avoid it? XML Data Islands only works with Internet Explorer browsers. Bind the XML document to an <xml> tag in the HTML document.xml"></xml> <table border="1" datasrc="#cdcat"> <tr> <td><span datafld="ARTIST"></span></td> <td><span datafld="TITLE"></span></td> </tr> </table> </body> </html> Try it yourself » The datasrc attribute of the <table> tag binds the HTML table to the XML data island. As the XML is read. The id attribute defines an id for the data island. In this case. "ARTIST" and "TITLE". additional rows are created for each <CD> element. What to use instead? You should use JavaScript and XML DOM to parse and display XML in HTML.xml". XML Data Island Example This example uses the XML document "cd_catalog. visit our XML DOM tutorial. The <span> tags allow the datafld attribute to refer to the XML element to be displayed.
  htc) } </style> </head> <body> <h1>Mouse over me!!!</h1> </body> </html> The XML document "behave.style.Behaviors What is it? Internet Explorer 5 introduced behaviors.Mouseover Highlight The following HTML file has a <style> element that defines a behavior for the <h1> element: <html> <head> <style type="text/css"> h1 { behavior: url(behave. What to use instead? Use JavaScript and XML DOM (or HTML DOM) instead. Example 1 .Internet Explorer . } function low_lite() { .htc" is shown below (The file contains a JavaScript and event handlers for the elements): <attach for="element" event="onmouseover" handler="hig_lite" /> <attach for="element" event="onmouseout" handler="low_lite" /> <script type="text/javascript"> function hig_lite() { element.color='red'. Why avoid it? The behavior attribute is only supported by Internet Explorer. Behaviors are a way to add behaviors to XML (or HTML) elements with the use of CSS styles.
  Behaviors are a way to add DHTML functionality to HTML elements with the ease of CSS.htc). } </script> Try it yourself » Example 2 . } </style> </head> <body> <span id="typing" speed="100">IE5 introduced DHTML behaviors.text2.text1. font-family:'courier new'.textLength. .<br /><br />How do behaviors work?<br /> By using XML we can link behaviors to any element in a web page and manipulate that element.t.</p>v </span> </body> </html> The XML document "typing.style.htc" is shown below: <attach for="window" event="onload" handler="beginTyping" /> <method name="type" /> <script type="text/javascript"> var i.element.color='blue'.Typewriter Simulation The following HTML file has a <style> element that defines a behavior for elements with an id of "typing": <html> <head> <style type="text/css"> #typing { behavior:url(typing.
  innerText="". } } </script> Try it yourself » Below is a list of XML technologies. t=window. etc XPath .transforms XML into other formats. element.type()".i+1).innerText=text2.setInterval(element. like HTML XSL-FO (XSL Formatting Objects). XML DOM (XML Document Object Model) A standard document model for accessing and manipulating XML.id+".substring(i.innerText.length.a language for navigating XML documents . XHTML (Extensible HTML) A stricter and cleaner XML based version of HTML. i=i+1. } function type() { text2=text2+text1. text1=element. XSL (Extensible Style Sheet Language) XSL consists of three parts: XSLT (XSL Transform) . element. paper.for formatting XML to screen. textLength=text1.speed).function beginTyping() { i=0. if (i==textLength) { clearInterval(t). text2="".
  XQuery (XML Query Language) An XML based language for querying XML data. SOAP (Simple Object Access Protocol) An XML-based protocol to let applications exchange information over HTTP. Some examples of how XML can be used to exchange information. SMIL (Synchronized Multimedia Integration Language) A language for describing audiovisual presentations. DTD (Document Type Definition) A standard for defining the legal elements in an XML document. XLink (XML Linking Language) A language for creating hyperlinks in XML documents. SVG (Scalable Vector Graphics) Defines graphics in XML format. WSDL (Web Services Description Language) An XML-based language for describing web services. XPointer (XML Pointer Language) Allows the XLink hyperlinks to point to more specific parts in the XML document. Example: XML News . XForms (XML Forms) Uses XML to define form data. XSD (XML Schema) An XML-based alternative to DTD. RSS (Really Simple Syndication) A format for syndicating news and the content of news-like sites. RDF (Resource Description Framework) An XML-based language for describing web resources.
  and archive any kind of news information across different hardware.0" encoding="ISO-8859-1" ?> <current_observation> <credit>NOAA's National Weather Service</credit> <credit_URL></credit_URL> <image> . Associated Press Writer</bytag> </byline> <dateline> <location>Bogota.XMLNews is a specification for exchanging news and other information.0" encoding="ISO-8859-1"?> <nitf> <head> <title>Colombia Earthquake</title> </head> <body> <headline> <hl1>143 Dead in Colombia Earthquake</hl1> </headline> <byline> <bytag>By Jared Kotler. receive. An example XMLNews document: <?xml version="1. Colombia</location> <date>Monday January 25 1999 7:28 ET</date> </dateline> </body> </nitf> Example: XML Weather Service An example of an XML national weather service from NOAA (National Oceanic and Atmospheric Administration): <?xml version="1. and programming languages. software. Using such a standard makes it easier for both news producers and news consumers to produce.
  23</pressure_in> <dewpoint_f>-11</dewpoint_f> <dewpoint_c>-24</dewpoint_c> <windchill_f>-7</windchill_f> <windchill_c>-22</windchill_c> <visibility_mi>10.gov/disclaimer. Kennedy Intl Airport.gov/disclaimer.gov/images/xml_logo.00</visibility_mi> <icon_url_base>. NY</location> <station_id>KJFK</station_id> <latitude>40.gov</link> </image> <location>New York/John F.6</pressure_mb> <pressure_in>30.html</disclaimer_url> <copyright_url></longitude> <observation_time_rfc822>Mon.66</latitude> <longitude>-73.jpg</icon_url_name> <disclaimer_url></copyright_url> </current_observation> If you are serious about XML.<url>..gif</url> <title>NOAA's National Weather Service</title> <link>. you will benefit from using a professional XML Editor. .gov/weather/images/fcicons/</icon_url_base> <icon_url_name>nfew.
  Personally I often use Notepad for quick editing of simple HTML.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 texteditor like Notepad. if you use Notepad for XML editing. But. so it will not be able to assist you. you will soon run into problems. CSS. . Notepad does not know that you are writing. Why an XML Editor? Today XML is an important technology. However. and XML files. when you start working with XML.
  C++.Professional XML editors will help you to write error-free XML documents. and C# Read more about XMLSpy XMLSpy is just one of the six tools in the Altova MissionKit® XML software suite. and debugger SOAP client and debugger Graphical WSDL 1. . validate your XML against a DTD or a schema.0/2. and force you to stick to a valid XML structure.0 editor. Read more about the Altova MissionKit for XML Developers.0 auto-completion XSLT 1. These are some of the features we especially like: Now available in 32-bit and 64-bit versions Easy to use Context-sensitive entry helpers Syntax coloring and pretty printing Built in validation & well-formedness checking Easy switching between text view and grid view Graphical XML Schema editor Database import and export for all major databases SharePoint® Server support Built in templates for many XML document types Chart creation for displaying XML data Intelligent XPath 1. and debugger XQuery editor.0/2. XMLSpy is our favorite XML editor. profiler. profiler. An 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 At W3Schools we have been using XMLSpy for many years.0 editor XBRL validation & taxonomy editing Support for Office 2007 / OOXML Code generation in Java.1/2.
  we recommend DTD and XML Schema. share. XML has very simple syntax rules. If you want to learn more about validating XML. please visit our XML DOM tutorial. XML documents form a tree structure that starts at "the root" and branches to "the leaves". JavaScript. The XML DOM is platform and language independent and can be used by any programming language like Java. Our XML examples also represent a summary of this XML tutorial. If you want to learn more about the DOM. and store data. Below is a short description of each subject. . XML DOM (Document Object Model) The XML DOM defines a standard way for accessing and manipulating XML documents. and VBScript. XML with correct syntax is "Well Formed". XML Namespaces provide a method to avoid element name conflicts. The XMLHttpRequest object provides a way to communicate with a server after a web page has loaded. All modern browsers have a built-in XML parser that can read and manipulate XML. Text inside a CDATA section is ignored by the parser. XSLT is used to transform XML into other formats like HTML.XML Summary XML can be used to exchange. Valid XML also validates against a DTD. The DOM (Document Object Model) defines a standard way for accessing XML. What to Study Next? Our recommendation is to learn about the XML DOM and XSLT.
  XML formatting and XML transformation (XSLT). and XML Schema use XML Syntax. Unlike DTD. If you want to learn more about XML Schema. These examples demonstrate XML files. If you want to learn more about XSLT. With DTD. please visit our XML Schema tutorial. XML Schema XML Schema is an XML based alternative to DTD. If you want to learn more about DTD. Viewing XML Files View a simple XML file (note. each of your XML files can carry a description of its own format with it. attributes and entities is legal in an XML document. They also demonstrate JavaScript used together with XML (AJAX). and your own data. please visit our XSLT tutorial. please visit our DTD tutorial.xml) View the same XML file with an error View an XML CD catalog . XML DTD (Document Type Definition) The purpose of a DTD is to define what elements. is valid. like XHTML.XSLT (XML Stylesheet Language Transformations) XSLT is the style sheet language for XML files. XML Schemas has support for datatypes. With XSLT you can transform XML documents into other formats. DTD can be used to verify that the data you receive.
  View an XML plant catalog View an XML food menu Examples explained XML and CSS View an XML CD catalog View the corresponding CSS file Display the CD catalog formatted with the CSS file Examples explained XML and XSLT View an XML food menu View the corresponding XSLT stylesheet Display the food menu styled with the XSLT stylesheet Examples explained Parsing XML and the XML DOM View a simple XML file (note.Crossbrowser example Examples explained XML to HTML View an XML CD catalog Display XML data in an HTML table Examples explained .Crossbrowser example Parse an XML string .xml) Parse the XML file .
  XML Applications View an XML CD catalog Show XML data inside an HTML div element Navigate through XML nodes A simple CD catalog application Examples explained XML Output From a Server See how ASP can return XML See how PHP can return XML View XML output from a database Examples explained XML DOM Advanced Get the value of an XML element Get the value of an XML attribute Change the value of an XML element Add a new attribute to an XML element Create a new XML element Remove an XML element Examples explained .
  This action might not be possible to undo. Are you sure you want to continue?
  We've moved you to where you read on your other device.
  Get the full title to continue reading from where you left off, or restart the preview.