AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 131


PART I


for (var i=0;i<versions.length;i++)
{
try
{
xmlDoc = new ActiveXObject(versions[i]);
break;
}
catch(err){}
}
}
else
xmlDoc = document.implementation.createDocument("", "", null);
return xmlDoc;
}

Interestingly, despite having an XML document in hand, it is still necessary to create the
processing instruction:

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

manually. Here there are more quirks; some browsers like Opera provide such a processing
directive while most others do not. Internet Explorer does not insert an encoding value, though
given what we learned in previous sections about character encoding and the current
ubiquity of UTF-8 it should be added.

if (window.navigator.userAgent.indexOf("Opera") == -1)
{
var xmlStmt = xmlDoc.createProcessingInstruction("xml"," version=\"1.0\"
encoding=\"UTF-8\" ");
xmlDoc.appendChild(xmlStmt);
}

Now it is time to create the packet using the createElement() and createTextNode()
DOM methods.

var vote = xmlDoc.createElement("vote");
var ratingNode = xmlDoc.createElement("rating");
ratingNode.appendChild(xmlDoc.createTextNode(ratingVal));
vote.appendChild(ratingNode);

var commentNode = xmlDoc.createElement("comment");
commentNode.appendChild(xmlDoc.createTextNode(comment));
vote.appendChild(commentNode);
xmlDoc.appendChild(vote);

At this point, you should have an XML DOM tree like so.

vote

comment

“I like it!”

rating

“3”
Free download pdf