XML Parsing in HTML 5
using jQuery;
Sample XML: File name
helpXml.xml
<?xml
version="1.0" encoding="utf-8"?>
<root >
<pointText xPos="" yPos=""
posture="">
<![CDATA[Point to each highlighted area to
learn more about the specific area. <br>Press Esc to exit help.]]>
</pointText >
<exitText xPos="" yPos="" posture="">
</exitText >
<courseTitle heading=""
xPos="50" yPos="65" posture="TR">
<![CDATA[Course Title <br>The name of the course.]]>
</courseTitle >
<frameTitle heading=""
xPos="150" yPos="100" posture="TR">
<![CDATA[Page Title <br>The name of the current page.]]>
</frameTitle >
<moduleTitle heading=""
xPos="35" yPos="100" posture="TR">
<![CDATA[Module Title <br>The name of the current module.]]>
</moduleTitle >
Parsing:
//Create an object
var
helpData = [];
$(document).ready(function(e) {
$.ajax({
type:
"GET",
url:
"helpXml.xml",
dataType:
"xml",
success:
helpParse //function name
});
});
function helpParse(xml){
//Creating an XML object of root node” helpContent”
var xmlObj=$(xml).find("root");
//Fetching the number of Element in root node
var elementLength =
xmlObj.children(this).length;
for(var i=0; i
helpData[xmlObj.children(this)[i].tagName]
= []
helpData[xmlObj.children(this)[i].tagName]['text']
= xmlObj.children(this)[i].textContent
//Retrieving the attributes of node
for(var
j=0; j
helpData[xmlObj.children(this)[i].tagName][xmlObj.children(this)[i].attributes[j].name]
= xmlObj.children(this)[i].attributes[j].value
}
}
alert(helpData[' courseTitle '].text)
//Result : Course Title <br>The name of the course.
alert(helpData[' courseTitle '].xPos)
// Result: 50
}
$(xml).find("root"): Returns the object of Root node
children: Returns the childNodes(Object)
tagName: Returns the childNode Name
textContent: Returns the value of childNode
attributes: Returns the attribute object
attributes[0].name: Returns the name of attribute
attributes[0].value: Returns the value of attribute
