Sie sind auf Seite 1von 15

XML:

Xml has a root element then it can have child element and attributes together
and child elements can have attribute and child elements.
Consider the below example:

<?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>

<to>Hume</to>
<from>Havt</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

<to>hooman</to>
<from>Jose</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

This example is wrong because root element (note) has child elements which
are repetatives (from, to, heading, body). To be able to have this
information we should have something like the below xml code:

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


<note>
<email>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

<email>
<to>Hume</to>
<from>Havt</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

<email>
<to>hooman</to>
<from>Jose</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

</note>
So the root element is note and then the child element is email but we have
three different emails. That is like a one to many relationship in an ER
diagram.

We can have attributes as well like:


<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<email id=123>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

< email id=124>


<to>Hume</to>
<from>Havt</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

< email id=126>


<to>hooman</to>
<from>Jose</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

</note>

Or even we can have something like that

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


<note>
<email id=123 to=”Jack” from=”Jane” heading=”Hi” body=”Kiss me”></email>
</note>

This is not a well-designed xml because we can have those attributes as


elements but attribute id is different because id doesn’t represent any
information and is only a way to make any email unique so we can
differentiate between different emails so in this case we can say that id is
meta-data(data about data) and it can be a rule that:
Meta-Data should be attribute

Display data in an xml file – Link html with xml


This is note.xml file:

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


<note>
<email>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

<email>
<to>Hume</to>
<from>Havt</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

<email>
<to>hooman</to>
<from>Jose</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</email>

</note>

And this is the html file:


<html>
<body>

<xml id="cdcat" src="note.xml"></xml>

<table border="1" datasrc="#cdcat">


<tr>
<td><span datafld="from"></span></td>
<td><span datafld="to"></span></td>
</tr>
</table>

</body>
</html>

The datasrc attribute of the <table> tag binds the HTML table element to the XML
data island. The datasrc attribute refers to the id attribute of the data island.

<td> tags cannot be bound to data, so we are using <span> tags. The <span> tag
allows the datafld attribute to refer to the XML element to be displayed. In this case,
it is datafld="from" for the <from> element and datafld="to" for the <to> element
in the XML file. As the XML is read, additional rows are created for each <emai>
element.

XML is case-sensetive so if we put ‘FROM’ for ‘datafld’ instead of ‘from’ then we


won’t see the content of xml file
Parsing Xml:

We can parse an xml file in different browsers, in IE 5+, firefox, opera.

To create an instance of Microsoft's XML parser, use the following code:

JavaScript:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

VBScript:
set xmlDoc=CreateObject("Microsoft.XMLDOM")

Asp:
set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")

The following code fragment loads an existing XML document ("note.xml") into
Microsoft's XML parser:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note.xml");

The first line of the script above creates an instance of the XML parser. The second
line turns off asynchronized loading, to make sure that the parser will not continue
execution of the script before the document is fully loaded. The third line tells the
parser to load an XML document called "note.xml".

In Mozila, firefox, Opera and etc:


xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("note.xml");

The following example is a cross browser example that loads an existing XML
document ("note.xml") into the XML parser:

<html>
<head>
<script type="text/javascript">
var xmlDoc;
function loadXML()
{
// code for IE
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("note.xml");
getmessage();
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation &&
document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("note.xml");
xmlDoc.onload=getmessage;
}
else
{
alert('Your browser cannot handle this script');
}
}
function getmessage()
{
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body onload="loadXML()">
<h1>W3Schools Internal Note</h1>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>

To extract the text (Jani) from an XML element like: <from>Jani</from>, the correct
syntax is:
etElementsByTagName("from")[0].childNodes[0].nodeValue

IMPORTANT: getElementsByTagName returns an array of nodes. The array contains


all elements with the specified name within the XML document. In this case there is
only one "from" element, but you still have to specify the array index ( [0] ).

How to load and parse an xml:


<html>
<body>
<script type="text/javascript">
var text="<note>";
text=text+"<to>Tove</to>";
text=text+"<from>Jani</from>";
text=text+"<heading>Reminder</heading>";
text=text+"<body>Don't forget me this weekend!</body>";
text=text+"</note>";
// code for IE
if (window.ActiveXObject)
{
var doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(text);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(text,"text/xml");
}
// documentElement always represents the root node
var x=doc.documentElement;
document.write("Text of first child element: ");
document.write(x.childNodes[0].childNodes[0].nodeValue);
document.write("<br />");
document.write("Text of second child element: ");
document.write(x.childNodes[1].childNodes[0].nodeValue);
</script>
</body>
</html>

Note: Internet Explorer uses the loadXML() method to parse an XML string, while
Mozilla browsers uses the DOMParser object.

Naming conlicts:
Consider two below xml file:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

And second one:


<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
Now if we add these two different xml file there would be a conflict because they
both have ‘table’ element.

So what should we do? Clearly we should do something to make them unique. This
can be a way:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

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

So we would name something called “NAME SPACE” and it means a space in which
the name exists. Now if we have different name spaces then we will have unique
names. Namespace is similar to family name we can have 1000000 john in a city
but belonging to different namespaces or here different family names.

In xml a namespace is called XMLNS or xml namespace.

The XML namespace attribute is placed in the start tag of an element and has the
following syntax:
xmlns:namespace-prefix="namespaceURI"

So in our last examples:


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

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

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/1999/XSL/Transform":
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr>
<th align="left">Title</th>
<th align="left">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>

Illegal XML characters have to be replaced by entity references.

There are 5 predefined entity references in XML:

&lt; < less than


&gt; > greater than
&amp; & ampersand
&apos; ' apostrophe
&quot; " quotation mark

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 example above, everything inside the CDATA section is ignored by the parser.

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.

Encoding attribute:

Encoding attribute should be in the xml tag to prevent having an error.


<?xml version="1.0" encoding="UTF-16"?>
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.

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 the HTML table element to display 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
datasrc attribute to bind the elements to the Data Island, and the datafld 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>

Look at this example:


<html>

<head>

<script type="text/javascript">

function testclick(field)

var row=field.rowIndex

xmldso_list.recordset.absoluteposition=row

td_title.innerHTML=xmldso_list.recordset("TITLE")

td_artist.innerHTML=xmldso_list.recordset("ARTIST")

td_year.innerHTML=xmldso_list.recordset("YEAR")
td_country.innerHTML=xmldso_list.recordset("COUNTRY")

td_company.innerHTML=xmldso_list.recordset("COMPANY")

td_price.innerHTML=xmldso_list.recordset("PRICE")

</script>

</head>

<body>

<xml id="xmldso_list" src="cd_catalog.xml"></xml>

<table border="1" bgcolor="yellow">

<tr align="left"><th>Title: </th><td id="td_title"></td></tr>

<tr align="left"><th>Artist: </th><td id="td_artist"></td></tr>

<tr align="left"><th>Year: </th><td id="td_year"></td></tr>

<tr align="left"><th>Country:</th><td id="td_country"></td></tr>

<tr align="left"><th>Company:</th><td id="td_company"></td></tr>

<tr align="left"><th>Price: </th><td id="td_price"></td></tr>

</table>

<p><b>Click on one of the CDs in the list:</b></p>

<table datasrc="#xmldso_list" border="1">

<thead>

<tr align="left">

<th>Title</th>

<th>Artist</th>

<th>Country</th>

<th>Company</th>

<th>Price</th>

<th>Year</th>

</tr>

</thead>
<tr align="left" onclick="testclick(this)">

<td><div datafld="TITLE" /></td>

<td><div datafld="ARTIST" /></td>

<td><div datafld="COUNTRY" /></td>

<td><div datafld="COMPANY" /></td>

<td align="right"><div datafld="PRICE" /></td>

<td><div datafld="YEAR" /></td>

</tr>

</table>

</body>

</html>

Using XMLHttpRequest object:


<html>

<head>

<script type="text/javascript">

var xmlhttp

function loadXMLDoc(url)

xmlhttp=null

// code for Mozilla, etc.

if (window.XMLHttpRequest)

xmlhttp=new XMLHttpRequest()

// code for IE

else if (window.ActiveXObject)

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}

if (xmlhttp!=null)

xmlhttp.onreadystatechange=state_Change

xmlhttp.open("GET",url,true)

xmlhttp.send(null)

else

alert("Your browser does not support XMLHTTP.")

function state_Change()

// if xmlhttp shows "loaded"

if (xmlhttp.readyState==4)

// if "OK"

if (xmlhttp.status==200)

document.getElementById('T1').innerHTML=xmlhttp.responseText

else

alert("Problem retrieving data:" + xmlhttp.statusText)

</script>

</head>
<body onload="loadXMLDoc('test_xmlhttp.txt')">

<div id="T1" style="border:1px solid black;height:40;width:300"></div><br />

<button onclick="loadXMLDoc('test_xmlhttp2.txt')">Click</button>

</body>

</html>

XMLHttpRequest object refrence:

Methods
Method Description

abort() Cancels the current request

getAllResponseHeaders() Returns the complete set of http headers as a


string

getResponseHeader("headername") Returns the value of the specified http header

open("method","URL",async,"uname" Specifies the method, URL, and other optional


,"pswd") attributes of a request

The method parameter can have a value of


"GET", "POST", or "PUT" (use "GET" when
requesting data and use "POST" when sending
data (especially if the length of the data is
greater than 512 bytes.

The URL parameter may be either a relative


or complete URL.

The async parameter specifies whether the


request should be handled asynchronously or
not. true means that script processing carries
on after the send() method, without waiting
for a response. false means that the script
waits for a response before continuing script
processing

send(content) Sends the request

setRequestHeader("label","value") Adds a label/value pair to the http header to


be sent

Properties
Property Description

onreadystatechange An event handler for an event that fires at every state


change

readyState Returns the state of the object:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

responseText Returns the response as a string

responseXML Returns the response as XML. This property returns an XML


document object, which can be examined and parsed using
W3C DOM node tree methods and properties

status Returns the status as a number (e.g. 404 for "Not Found" or
200 for "OK")

statusText Returns the status as a string (e.g. "Not Found" or "OK")

Das könnte Ihnen auch gefallen