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>
Related
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);
}
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>
I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
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.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";
Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
var xmlhttp;
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.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.
Hi I have the following code
<html>
<head>
<script type="text/javascript">
var xmlhttp;
var allSearchResults = [];
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction(paramm)
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
if (txt.match(paramm)!= -1){
//store all instances in allSearchResults array Here
}
else{
document.getElementById("myDiv").innerHTML = paramm;
}
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction('CXS101289')">Change Content</button>
</body>
</html>
ajax_info.txt
CXS101289_5_R1A06_100628150914
CXS101289_5_R1A06_100628343414
CXS10rfe_5_R1A06_100628150955
CXS101349_5_R1A06_100628150432
CXS154f89_5_R1A06_100628150914
CXS101289_5_R1A06_10062456914
CXS101369_5_R1A06_100628150914
CXS15679_5_R1A06_100628150914
So I want to search this file for the "CXS101289". So after I have run this method, the "allsearchResults" array shall contain ["CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_10062456914"]
Any smart idea on how to implement this?
This should do what you're looking for
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"));
for example after
param = "x";
txt = "x_1 y_2 z_3 x_4 yx_5 z_6 x_7";
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"))
result is ["x_1", "x_4", "x_7"]
Note that if param is going to contain charaters that have a special meaning for a regular expression (for example * or + or ]) then you have to escape them by prepending a backslash.
The initial \b is needed to be sure that your search key is only accepted at the beginning of an item.
function findMatched(text, keyword) {
var arr = text.split('\n');
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(arr[i].match(keyword)) {
result.push(arr[i]);
}
}
return result;
}
//...and in your code
if (txt.match(paramm)!= -1){
allSearchResults = findMatched(txt, paramm);
}
It is the only way I can see it solve. But maybe you already taught of this and where asking something else.