Syntax Error? When parsing XML value - javascript

I don't know if I'm having a syntax error but the compiler is giving me
TypeError: 'undefined' is not an object (evaluating
'xmlDoc.getElementsByTagName("icon")[count].childNodes')
Its me giving me this problem when im parsing the XML from my server, my actual javascript code is like this
var xmlDoc = Obj.responseXML;
var count = 0;
if(xmlDoc){
while(count <= xmlDoc.getElementsByTagName("item").length){
document.getElementById("flow").innerHTML += "<div class='item'><img class='content' src='" + xmlDoc.getElementsByTagName("icon")[count].childNodes[0].nodeValue.replace(/\s+$/g,' ') +"' /></div>";
count++;
}
}else{
alert("Unable to parse!");
}
and my XML goes like this.
<feed>
<item>
<title>Given Title</title>
<icon>
http://i178.photobucket.com/albums/w255/ace003_album/Logo-ETC-RGB-e1353503652739.jpg
</icon>
</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</feed>
i just want to parse the image link and to show it.
DOM parser
var url = "http://myURL.com/document.xml";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else
{
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
Obj.open("POST",url,false);
Obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Obj.send();

Demo
Firstly, you're while loop condition should be just < not <=. By using the latter, the loop is running one too many times, causing the error because the index is out of bounds.
Secondly, in the while loop you're getting the icon elements based on the count from the root of the document. The icon's are children of each item so you should retrieve the icon relative to the item by using item.getElementsByTagName('icon')[0] not xmlDoc.getElementsByTagName('icon')[count].
Not related to the problem but building HTML as strings like that is undesirable. Creating the elements and inserting them into the DOM would be better because you don't need to handle any escaping. Also, store a reference to flow before the while, instead of finding it on each iteration.
var div;
var img;
var flow = document.getElementById('flow');
var items = xmlDoc.getElementsByTagName("item");
while(count < items.length){
div = document.createElement('div');
div.className = 'item';
img = document.createElement('img');
img.className = 'content';
img.src = items[count].getElementsByTagName("icon")[0].childNodes[0].nodeValue.replace(/\s+$/g,' ');
div.appendChild(img);
flow.appendChild(div);
count++;
}

Related

How to get the attribute Value of an xml tag created with namespace?

<root xmlns='http://www.w3.org/2005/Atom' xmlns:element='http://search.yahoo.com/mrss/'>
<element:group>
<element:content url='https://myrequiredurl.com' otherattr='360' otherattr='640' otherattr='somthng' medium='smtng'/>
<element:content url='https://myrequiredurl.com' otherattr='720' otherattr='1280' otherattr='smtng' medium='smtng'/>
<element:content url='https://myrequiredurl.com' otherattr='1080' otherattr='1920' otherattr='smtng' medium='smtng'/>
</element:group>
</root>
Above is my xml doc i need to get the 'url' attribute from first '<element:content/>' tag i tried the ways mentioned in w3schools.com but i had
no luck some help is much appreciated i need to access it using javascript sorry for bad question framing
You can simply achieve this using dom manupulation.
HTML:
<p id="show"></p>
Javascript:
var urlList = [];
var txt = "<root xmlns='http://www.w3.org/2005/Atom' xmlns:element='http://search.yahoo.com/mrss/'>" +
"<element:group>" +
"<element:content url='https://1myrequiredurl.com' otherattr='somthng' medium='smtng'> </element:content>" +
"<element:content url='https://2myrequiredurl.com' otherattr='smtng' medium='smtng'> </element:content>" +
"<element:content url='https://3myrequiredurl.com' otherattr='smtng' medium='smtng'> </element:content>" +
"</element:group>" +
"</root>";
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // For Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var group = xmlDoc.getElementsByTagName("root")[0].childNodes[0].childNodes;
for (var content in group) {
if (!isNaN(content)) {
var url = group[content].getAttribute("url")
urlList.push(url);
}
}
document.getElementById("show").innerHTML = urlList.join("</br>");
P.S: "You cannot add multiple attributes with the same name".
you can find the solution here: https://jsfiddle.net/vineetsagar7/3od130pd/2/

Content Fetching from XML file

I have a xml content as below
<tty>
<xyz id="1">
<yzx>ghs</yzx>
<dfg>kli</dfg>
</xyz>
<xyz id="2">
<yzx>sss</yzx>
<dfg>ddd</dfg>
</xyz>
</tty>
I need to fetch the content of xyz also and when I try to do so I face an error stating
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "file.xml",false);
xmlHttp.send();
xmlDoc = xmlHttp.responseXML;
var wee= xmlDoc.getElementsByTagName("xyz");
for(var i=0; i<wee.length;i++){
var name = wee[i].childNodes[0].nodeValue;
var yzx = wee[i].childNodes[1].nodeValue;
var dfg= wee[i].childNodes[2].nodeValue;
error is
Cannot read property childnode
My output should have like below
name 1
yzx ghs
you are using getElementsByTagName twice :)
wee is already all of the <xyz> tags, and there are no more <xyz> tags below it. That means the getElementsBbyTagName('xyz') inside the for loop will return nothing.
You probably just want
for(var i = 0; i < wee.length; i++) {
var name = wee[i].childNodes[0].nodeValue; // "yzx" node
}
instead.

print entire xml data and tags in html - javascript [duplicate]

I want to convert an xml element like this:
<asin>​B0013FRNKG​</asin>​
to string in javascript
I used XMLSerializer:
new XMLSerializer().serializeToString(xml);
the string only shows on alert() and in the console. On the page it just says
[object Element][object Element]
I want to get the string.
You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:
document.getElementById('SomeDiv').appendChild(xml);
and if you just want the full xml string to be displayed:
var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);
<script type='text/javascript'>
function xmlToString(xmlData) {
var xmlString;
//IE
if (window.ActiveXObject){
xmlString = xmlData.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else{
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
}
</script>
use this in case of IE for browser compatibility issues.
function getXmlString(xml) {
if (window.ActiveXObject) { return xml.xml; }
return new XMLSerializer().serializeToString(xml);
}
alert(getXmlString(xml));
Did you try enclosing the result like in…
(new XMLSerializer()).serializeToString(xml)
Also, I'd use console instead to see the content better:
console.log((new XMLSerializer()).serializeToString(xml));
If the DOM element <asin>​B0013FRNKG​</asin>​ is stored in the object element, then you can access the value using:
element.textContent
follow this to print,append data from xml data stored as string inside javscript
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);//finaly it becomes <div id="element_id">athor<br></div>
}

How to display images using Javascript and JSON

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

MSIE: Append XML Element to HTML Element

I'm using an XMLHttpRequest to retrieve XML from the server, and I'd like to append it to an existing HTML node on the page. It's well formed HTML and I've added xmlns='http://www.w3.org/1999/xhtml' to the XML root element in the response: works fine for Firefox, but IE bombs with "No such interface supported", I guess because it's got the node I'm trying to append typed as "IXMLDOMElement".
Here's the XML response:
<qstat xmlns='http://www.w3.org/1999/xhtml'>
<ul>
<li><b>Cycle number:</b> 6</li>
<li><b>Error:</b> none</li>
</ul>
</qstat>
And here's the Javascript:
var req = new XMLHttpRequest()
req.onreadystatechange = function() {
if(req.readyState == 4)
{
dom = req.responseXML;
var nodes = dom.firstChild.childNodes; //Everything under the root node.
var ele = document.getElementById("qstat");
for(var i=0; i<nodes.length; i++)
{
ele.appendChild(nodes[i]); // BOMBS HERE.
}
}
};
The MSIE Debugger (MSIE 8) correctly identifies nodes[0] as having tagName=ul and even has namespaceURI="http://www.w3.org/1999/xhtml", but I guess because it's type is IXMLDOMElement, the call doesn't work.
So is there any way to convert the objects in nodes to corresponding HTML node objects that I can append to the element?
Try following:
1) create an HTML element
var factory = document.createElement("div");
2) serialize the fetch XML element
var xml = nodes[i].xml || new XMLSerializer().serializeToString(nodes[i]);
3) render xml through innerHTML
factory.innerHTML = xml;
4) get firstChild from factory element which is now HTML element
var eleHTML = factory.firstChild;
5) append eleHTML to where you need it:
ele.appendChild(eleHTML);
Hint: you can reuse once created factory DOMHTML element

Categories