Get value from XML file Using JavaScript - javascript

I am having a some problems in getting a node value from a XML file
My XML looks like this:
<item>
<item1><Description>test</Description></item1>
<item2><Description>test2</Description></item2>
<item3><Description>test3</Description></item3>
</item>
And I am trying to get 'test2' from Item2 > Description.
I am able to get the xml file display in a alert messagebox but can't seem to get the value i am looking for.
I am trying to do this in JavaScript and so far I have come up with the following:
function get_item()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
xmlDoc = xmlhttp.responseText;
var item = xmlDoc.getElementsByTagName("Description")[0];
item = item.childNodes.length ? item.childNodes[0].nodeValue : "" ;
alert(item)
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","http://192.168.0.5/xml_file.xml",false);
xmlhttp.send();
}
If I remove:
var item = xmlDoc.getElementsByTagName("Description")[0];
item = item.childNodes.length ? item.childNodes[0].nodeValue : "" ;
and change the alert to:
alert(xmlDoc)
it alerts my XML file, so i know it's reading my xml file but can't get the value.
Am I doing something wrong or is there a better way to get this value?
(I don't want to use jQuery for this)

Use xmlhttp.responseXML instead of xmlhttp.responseText, I think there might be some issue with older versions of IE though, in which case you can try
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(xmlhttp.responseText);

This function you can use to parse XML and use this link (http://www.hiteshagrawal.com/javascript/javascript-parsing-xml-in-javascript).
function readXML()
{
if(xmlDoc.readyState == 4)
{
//Using documentElement Properties
//Output company
alert("XML Root Tag Name: " + xmlDoc.documentElement.tagName);
//Using firstChild Properties
//Output year
alert("First Child: " + xmlDoc.documentElement.childNodes[1].firstChild.tagName);
//Using lastChild Properties
//Output average
alert("Last Child: " + xmlDoc.documentElement.childNodes[1].lastChild.tagName);
//Using nodeValue and Attributes Properties
//Here both the statement will return you the same result
//Output 001
alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue);
alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("id").nodeValue);
//Using getElementByTagName Properties
//Here both the statement will return you the same result
//Output 2000
alert("getElementsByTagName: " + xmlDoc.getElementsByTagName("year")[0].attributes.getNamedItem("id").nodeValue);
//Using text Properties
//Output John
alert("Text Content for Employee Tag: " + xmlDoc.documentElement.childNodes[0].text);
//Using hasChildNodes Properties
//Output True
alert("Checking Child Nodes: " + xmlDoc.documentElement.childNodes[0].hasChildNodes);
}

Related

Retrieving all XML from nodes with Javascript

I'm trying to get the xml from nodes. Let's say I have an XML file:
<?xml version="1.0"?>
<story title="My title here">
<subject key="key1" caption="Intro">
Text here for subject 1. There might be an occasional <html> markup present.
<action tag="actiontag"/>
</subject>
<subject key="key2" caption="Chap1">
Text for chapter 2
<directions>
<dir go="chap5" to="Solving"/>
<dir go="chap12" to="Searching">
<extra1 subtitle="subtitle">You can expect extra text here as well.</extra>
<extra2 subtitle="subtitle2"/>
</dir>
<dir go="chap2,chap5" to="Finding"/>
</directions>
</subject>
<chapters key="chap1" caption="Chapter1">
The text for chapter1 goes here
<newtag>This one has text as well</newtag>
</chapters>
</story>
Now I'm trying to get the whole XML code including nodes and tags into an array of objects. So the result should ideally be:
subjects[0].key=key1
subjects[0].caption=Intro
subjects[0].txt=Text here for subject 1. There might be an occasional <html> markup present.<action tag="actiontag"/>
subjects[1].key=key2
subjects[1].caption=Chap1
subjects[1].txt=Text for chapter 2<directions><dir go="chap5" to="Solving"/><dir go="chap12" to="Searching"><extra1 subtitle="subtitle">You can expect extra text here as well.</extra><extra2 subtitle="subtitle2"/></dir><dir go="chap2,chap5" to="Finding"/></directions>
This 'text' can than later be processed as XML.
Now I've been able to read the XML and access the tags separately. I've been able to traverse through the file and get the text but I can't seem to loop through all the nodes/text/tags and keep it formatted as is.
What I have is:
var xmlDoc;
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xmlhttp.onloadend = init(xmlDoc);
}
function init(xmlDoc) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: x[i].childNodes[0].nodeValue });
}
//just to check if there's something recorded..
document.getElementById("result").innerHTML = subjects[1].txt;
}
The array of objects is no problem, that works. But how do I change x[i].childNodes[0].nodeValue to hold all the childnodes of [subject] and keep accompanying tags and formatting?
Thanks for your time.
function loadxml() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "assets/myfile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
responseText = xmlhttp.responseText;
textNodes = responseText.split(/<subject.*>/);
textNodes.shift(); //remove first chunk of text
for (var i = 0; i < textNodes.length; i++) {
textNodes[i] = textNodes[i].replace(/\r?\n|\r/g, ''); //remove line breaks;
textNodes[i] = textNodes[i].replace(/^\s*/, ''); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/>\s*/g, '>'); // Replace "> " with ">"
textNodes[i] = textNodes[i].replace(/\s*</g, '<'); // Replace "< " with "<"
}
xmlhttp.onloadend = init(xmlDoc, textNodes);
}
function init(xmlDoc, textNodes) {
var subjects = [];
var x, i;
x = xmlDoc.getElementsByTagName('subject');
for (i = 0; i < x.length; i++) {
subjects.push({ key: x[i].getAttribute('key'), caption: x[i].getAttribute('caption'), txt: textNodes[i] });
}
console.log(subjects);
}

Insert XML node value inside iframe src

Been trying everything and all i get is a blank page ...
The XML is provided by URL format and contains many nodes but i just want to take out the username and place it inside a iframe scr url.
optimal this will repeat for until no more usernames on that xml
Here is what i got so far
<script type="text/javascript">
if (window.XMLHttpRequest)
{
//Code for IE7,Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
//code for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://xml.url/here", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
//This code for printing attribute of a tag(you have to give attribute name).
document.write("<br>" + y[i].getAttributeNode('username').nodeName + ": ");
document.write(y[i].getAttributeNode('username').nodeValue + "<br>");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{
//This is for Node Name.
document.write(y[i].childNodes[z].nodeName + ": ");
//This is for Node Value.
document.write(y[i].childNodes[z].textContent + "<br>");
}
}
}
}
</script>
<iframe src="http://blablabla + 'username' + blablabla " height="300" width="400" style="border: none;"></iframe>

Unable to get property of GetElementsbyTagName of undefined or null reference

Let me start by stating I am a Newb and while I have created a fair bit of html code, I am trying to move into XML and Javascipt for my own edification. That being said, I have run into a problem (which I researched and found similar issues) that has stumped me. The funny thing the code worked a few times under Firefox but now it works on nothing and I can't seem to find the issue. I did use the IE Console to check file open status etc.. but no joy. As the subject line indicates I can't seem to list the XML tag(s) in a table I am building for a web page. Here is the relevant html code and associated XML file. Any assistance would be appreciated.
HTML Code
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","event.xml",true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState!=4)return;
if(xmlhttp.status==200)
alert(xmlhttp.responseText);
else
alert("Request failed!");
};
//onreadystatechange
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var y=xmlDoc.getElementsByTagName("months");
for (i=0;i<y.length;i++)
{
document.write("<tr bgcolor='#6CA6CD'>");
document.write("<th>");
document.write(month[i].getElementsByTagName("month1")[0].childNodes[0].nodeValue);
document.write("</th>");
document.write("<th>");
document.write(month[i].getElementsByTagName("month2")[0].childNodes[0].nodeValue);
document.write("</th>");
document.write("</tr>");
}
var x=xmlDoc.getElementsByTagName("month_event");
for (i=0;i<x.length;i++)
{
document.write("<tr><td bgcolor='white'>");
document.write("<b> ");
document.write(x[i].getElementsByTagName("month1_date")[0].childNodes[0].nodeValue);
document.write("</b> - ");
document.write(x[i].getElementsByTagName("month1_day")[0].childNodes[0].nodeValue);
document.write(" - ");
document.write(x[i].getElementsByTagName("month1_time")[0].childNodes[0].nodeValue);
document.write(" - ");
document.write(x[i].getElementsByTagName("month1_evdescription")[0].childNodes[0].nodeValue);
document.write("</td><td bgcolor='lightgrey'>");
document.write("<b> ");
document.write(x[i].getElementsByTagName("month2_date")[0].childNodes[0].nodeValue);
document.write("</b> - ");
document.write(x[i].getElementsByTagName("month2_day")[0].childNodes[0].nodeValue);
document.write(" - ");
document.write(x[i].getElementsByTagName("month2_time")[0].childNodes[0].nodeValue);
document.write(" - ");
document.write(x[i].getElementsByTagName("month2_evdescription")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
XML File:
<?xml version="1.0" encoding="UTF-8"?>
<events>
<months>
<month1>December</month1>
<month2>January</month2>
</months>
<month_event>
<month1_date>22 Dec</month1_date>
<month1_day>Sunday</month1_day>
<month1_time>10:30AM - 11:00AM</month1_time>
<month1_evdescription>The Centre is closed</month1_evdescription>
<month2_date>6 Jan</month2_date>
<month2_day>Tuesday</month2_day>
<month2_time>All Day</month2_time>
<month2_evdescription>The Heavy</month2_evdescription>
</month_event>
<month_event>
<month1_date>25 Dec</month1_date>
<month1_day>Wednesday</month1_day>
<month1_time>All Day</month1_time>
<month1_evdescription>Christmas</month1_evdescription>
<month2_date>10 Jan</month2_date>
<month2_day>Tuesday</month2_day>
<month2_time>10:30AM - 11:30AM</month2_time>
<month2_evdescription>Nothing</month2_evdescription>
</month_event>
</events>
getElementsByTagName returns a NodeList, not an array, so use x.item(i).
To get it to work, make the following changes:
1) change true to false for synchronous (line 11)
xmlhttp.open("GET","event.xml",false);
2) declare the month variable (line 31+)
for (i=0;i<y.length;i++)
{
var month = y.item(i); // insert this line
document.write("<tr bgcolor='#6CA6CD'>");
document.write("<th>");
document.write(month.getElementsByTagName("month1").item(0).childNodes[0].nodeValue); // !!!
3) use .item(i) and .item(0) rather than [i] and [0] (line 45+)
var x=xmlDoc.getElementsByTagName("month_event");
for (i=0;i<x.length;i++)
{
document.write("<tr><td bgcolor='white'>");
document.write("<b>test ");
document.write(x.item(i).getElementsByTagName("month1_date").item(0).childNodes[0].nodeValue);

XML Parsing with Javascript

I have an XML file which consists of multiple records and I want to display all of them on one page. I have written some code but it's not helping me out.
Here some tags are optional so how I can I show "--" in that optional tag where it is not appearing?
XML File
<doctors>
<doctor specialization="Gynaecologist">
<name>Alex Mashkin</name>
<bachelor_degree>MBBS</bachelor_degree>
<master_degree>Master in Gynaecology</master_degree>
<experience>7 Years</experience>
<available_timings>12PM to 5PM</available_timings>
<fees>500</fees>
<operation_charges>20000</operation_charges>
<special_visit_charges>1000</special_visit_charges>
</doctor>
<doctor specialization="Sergeon">
<name>Dazy Deepy</name>
<bachelor_degree>MBBS</bachelor_degree>
<master_degree>Master in Surgery</master_degree>
<experience>10 Years</experience>
<available_timings>11AM to 2PM</available_timings>
<fees>900</fees>
<operation_charges>25000</operation_charges>
<special_visit_charges>1800</special_visit_charges>
</doctor>
<doctor specialization="Dentist">
<name>Mona Bralia</name>
<bachelor_degree>BDS</bachelor_degree>
<experience>3 Years</experience>
<available_timings>4PM to 8PM</available_timings>
<fees>300</fees>
<special_visit_charges> 600</special_visit_charges>
</doctor> </doctors>
HTML Code
(snippet)
<script type="text/javascript">
if (window.XMLHttpRequest) {
//Code for IE7,Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
//code for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XMLFile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("doctor");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getAttribute("specialization"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("bachelor_degree")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("master_degree")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("experience")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("available_timings")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("fees")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("operation_charges")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("special_visit_charges")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
So, you want to iterate all <doctor> elements, and check the children of each. That means you can't just get all xmlDoc.getElementsByTagName("master_degree") from the document and think it's ith item would match the current doctor, as some doctors do not have a <master_degree> elemenent. Instead, check it for each of them by applying getElementsByTagName on the doctor itself, and count how many master degrees you have selected (might be none, might be more than one?).
// a mapping from HTML ids to XML tag names, to make it more programmatical
var map = {dname:"name", bdegree":"bachelor_degree", mdegree:"master_degree", exp:"experience", availibity:"available_timings, fee:"fees", opcharge:"operation_charges", spcharge:"special_visit_charges"};
// and from HTML ids to XML attribute names of the doctor
var attrmap = {spec:"specialisation"};
… // load XML etc - you should do it asynchronous, btw
var doctors = xmlDoc.getElementsByTagName("doctor"),
doctorCount = doctors.length;
for (var i=0; i<doctorCount; i++) {
var doc = doctors[i];
for (var id in map) {
var elements = doc.getElementsByTagName(map[id]),
var result = "";
if (!elements.length)
result = "---";
for (var j=0; j<elements.length; j++)
if (elements[i].firstChild)
result += elements[i].firstChild.data;
document.getElementById(id).innerText += result;
}
for (var id in attrmap) {
document.getElementById(id).innerText += doc.getAttribute(attrmap[id]);
}
}
After lot of research I have find out shortest way to iterate all the elements with attribute.
Here is the code:
<script type="text/javascript">
if (window.XMLHttpRequest)
{
//Code for IE7,Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
//code for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XMLFile.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
y=xmlDoc.documentElement.childNodes;
for (i=0;i<y.length;i++)
{
if (y[i].nodeType!=3)
{
//This code for printing attribute of a tag(you have to give attribute name).
document.write("<br>" + y[i].getAttributeNode('specialization').nodeName + ": ");
document.write(y[i].getAttributeNode('specialization').nodeValue + "<br>");
for (z=0;z<y[i].childNodes.length;z++)
{
if (y[i].childNodes[z].nodeType!=3)
{
//This is for Node Name.
document.write(y[i].childNodes[z].nodeName + ": ");
//This is for Node Value.
document.write(y[i].childNodes[z].textContent + "<br>");
}
}
}
}
</script>

GetXmlHttpObject AJAX call to a php file

I am trying to call a php file using GetXmlHttpObject object and having some luck, but seem to have problem with the URL variable.
Is there something I have to do with the URL string differently?
Here is the relevant code:
remoteCounter('marks');//invoking function
document.write("<div id=\"marks\"></div>");//destination div
function GetXmlHttpObject () {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari, IE 7+
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer - old IE - prior to version 7
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function remoteCounter(param){
counterObj = GetXmlHttpObject();
var url="HTTP://dnsname/directory/view.php?" + param;
alert(url + " " + counterObj);
counterObj.open("GET", url , true);
counterObj.onreadystatechange=updateCounter;
counterObj.send(null);
}
function updateCounter(){
//alert('updateCounter');
if (counterObj.readyState == 4 || counterObj.readyState == "complete"){
document.getElementById("marks").innerHTML=counterObj.responseText;
}
}
I can replace the counterObj.responseText variable in document.getElementById("marks").innerHTML=counterObj.responseText;
and see the test string correctly in the source document, so I know the html and jscript source is not the problem.
I have commented out code in the view.php file to just echo a simple string, but that is not showing either - which again makes me think the problem is in the request to the file, not in the file, not in the source.
Actual server name and directory have been replaced by dnsname/directory for this post. Including alert for debugging.
thank you for assistance.
Replace order of two first lines:
document.write("<div id=\"marks\"></div>"); //destination div
remoteCounter('marks'); //invoking function
It's necesary declarate div tag with id "marks" first.

Categories