Reputation: 49
I have this XML data set that I am working with:
<?xml version="1.0" encoding=UTF=8?>
<peopleNetwork>
<person id="1">
<name>Alice</name>
<friend>Ruby</friend>
<image>images/ruby.jpg</image>
</person>
<person id="2">
<name>Tom</name>
<friend>Katty</friend>
<image>images/ketty.jpg</image>
</person>
</peopleNetwork>
As you can see I have image tags with image paths, I have written a code shown in the fiddle - I am not sure what I am doing wrong but the path does not convert to actual image.
$("#container").append('<div class"peopleNetwork"><img src="images/' + $(xmlDoc).find("image").text() + '/><p>' + $(xmlDoc).find('person[id="1"]').text() + '</p></div>');
https://jsfiddle.net/3zg8nyat/
Can anyone help please.
Upvotes: 0
Views: 61
Reputation: 146540
First of all, your XML is malformed. That prevents it from being parsed by any dedicated tool. Where it says:
<?xml version="1.0" encoding=UTF=8?>
... it should say:
<?xml version="1.0" encoding="UTF-8"?>
Once you fix that, you need to parse your XML with jQuery.parseXML():
jQuery.parseXML
uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated.
var xml = $($.parseXML(xmlDoc))
var src = xml.find("image").text();
console.log(src);
See check an online demo.
Additional issues:
You don't close the quotes of the src
attribute:
'<img src="images/' + $(xmlDoc).find("image").text() + '/>'
You retrieve all images at once because jQuery.text() gets:
the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements
Upvotes: 1
Reputation: 929
The src
in your img
tag is coming out as images/images/filename.jpg
. Are the image files really in an images subdirectory within another images subdirectory?
Either remove the hardcoded images/
from your img
tag or take the images/
out of each <image>
node value in your XML.
Upvotes: 0