How to parse an XML object in Javscript - javascript

This is probably a relatively simple problem but I am finding it difficult to be able to parse my specific xml object in javascript.
My XML looks like this
<ns2:GetItemResponse xmlns:ns2="urn:ebay:apis:eBLBaseComponents">
<Ack>Success</Ack>
<Build>E1125_INTL_API_19070421_R1</Build>
<Item>
<AutoPay>false</AutoPay>
<BuyItNowPrice>0.0</BuyItNowPrice>
<BuyerProtection>ItemIneligible</BuyerProtection>
<Charity>
<CharityID>1135</CharityID>
<CharityName>The Humane Society of the United States</CharityName>
<CharityNumber>1726</CharityNumber>
<DonationPercent>10.0</DonationPercent>
<LogoURL>https://i.ebayimg.com/00/s/NzYyWDEzNzM=/z/K3EAAOSwFgNdVeRz/$_1.JPG?set_id=8800005007
</LogoURL>
<Mission>
The Humane Society of the United States is the nation's most effective animal protection organization. Since 1954, HSUS has been fighting for the protection of all animals through advocacy, education and hands-on programs. Together with our affiliates, we rescue and care for tens of thousands of animals each year, but our primary mission is to prevent cruelty before it occurs. We're there for all animals!
</Mission>
<Status>Valid</Status>
</Charity>
<Country>US</Country>
<Description>
<p dir="ltr">Wolverine #100 - April 1996 Marvel Comics The 100th Issue! Comic Book. </p>
</Description>
</Item>
<Timestamp>2020-02-13T14:19:33.939Z</Timestamp>
<Version>1125</Version>
</ns2:GetItemResponse>
I basically want to display the Item properties and Charity properties but I am finding it difficult to understand the child nodes of these objects I have tried doing this
parser = new DOMParser();
var obj = request.responseXML;
console.log(obj.getElementsByTagName("Item")[0]);
xmlDoc = parser.parseFromString(request.responseText, "text/xml");
// panel.innerHTML += "<br> " + xmlDoc.getElementsByTagName("ItemId")[0].childNodes[0].nodeValue ;
//console.log(xmlDoc.getElementsByTagName("Timestamp")[0].childNodes[0].nodeValue);
console.log(xmlDoc.getElementsByTagName("Item")[0].childNodes);
All help would be greatly appreciated

simple...
const docXML = `
<ns2:GetItemResponse xmlns:ns2="urn:ebay:apis:eBLBaseComponents">
<Ack>Success</Ack>
<Build>E1125_INTL_API_19070421_R1</Build>
<Item>
<AutoPay>false</AutoPay>
<BuyItNowPrice>0.0</BuyItNowPrice>
<BuyerProtection>ItemIneligible</BuyerProtection>
<Charity>
<CharityID>1135</CharityID>
<CharityName>The Humane Society of the United States</CharityName>
<CharityNumber>1726</CharityNumber>
<DonationPercent>10.0</DonationPercent>
<LogoURL>https://i.ebayimg.com/00/s/NzYyWDEzNzM=/z/K3EAAOSwFgNdVeRz/$_1.JPG?set_id=8800005007
</LogoURL>
<Mission>
The Humane Society of the United States is the nation's most effective animal protection organization. Since 1954, HSUS has been fighting for the protection of all animals through advocacy, education and hands-on programs. Together with our affiliates, we rescue and care for tens of thousands of animals each year, but our primary mission is to prevent cruelty before it occurs. We're there for all animals!
</Mission>
<Status>Valid</Status>
</Charity>
<Country>US</Country>
<Description>
<p dir="ltr">Wolverine #100 - April 1996 Marvel Comics The 100th Issue! Comic Book. </p>
</Description>
</Item>
<Timestamp>2020-02-13T14:19:33.939Z</Timestamp>
<Version>1125</Version>
</ns2:GetItemResponse>`;
const parser = new DOMParser()
, xmlDoc = parser.parseFromString(docXML, "text/xml");
console.log( '1st CharityName = ', xmlDoc.querySelector('Item CharityName').textContent )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Execute JS using Python and store results in an array

I am working on this website where there is an SVG map and radio buttons as filters :
To get the result of the filter in the map (countries colored in blue), I execute this javascript snippet :
var n = $("input[name=adoptionStatus]:checked").val();
(n == undefined || n === "") && (n = "00000000000000000000000000000000");
$(".status-text").hide();
$("#" + n).show();
$("#vmap").vectorMap("set", "colors", resetColorsData);
resetColorsData = {};
colorsData = {};
$("#countries_list a").each(function(t, i) {
$(i).data("adoption-status").indexOf(n) >= 0 && (colorsData[$(i).data("country-code")] = "#2f98cb", resetColorsData[$(i).data("country-codecountry-code")] = "#fefefe")
});
$("#vmap").vectorMap("set", "colors", colorsData)
The variable n is used to store the value of the radio button like in this case cae64c6b731d47cca7565b2a74d11d53 :
<div class="map-filter-radio radio">
<label>
<input type="radio" name="adoptionStatus" alt="IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions." title="IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions." value="cae64c6b731d47cca7565b2a74d11d53">
IFRS Standards are permitted but not required for domestic public companies
</label>
</div>
When I execute the Javascript in the console and try to get the colorsData, I get the list of the countries colored in blue like below :
bm: "#2f98cb"
ch: "#2f98cb"
gt: "#2f98cb"
iq: "#2f98cb"
jp: "#2f98cb"
ky: "#2f98cb"
mg: "#2f98cb"
ni: "#2f98cb"
pa: "#2f98cb"
py: "#2f98cb"
sr: "#2f98cb"
tl: "#2f98cb"
How can I execute the JS script on the webpage and get the result of the colored countries in an array using python ?
By looking at the list of countries specified by #countries_list, you got a list of a tag like the following :
<a id="country_bd" data-country-code="bd" data-adoption-status="97f9b22998d546f7856bb1b4f0586521|3adc18f07ff64c908a6d835e08344531|ff784361818644798ea899f81b8b6d61" href="/use-around-the-world/use-of-ifrs-standards-by-jurisdiction/bangladesh/">
<img src="/-/media/7bfd06a698594c2cb3614578a41caa9e.ashx" alt="Bangladesh">
Bangladesh
</a>
The data-adoption-status attribute is a list of adoptionStatus delimited by |.
You just need to split them and match only the countries that reference the value from the input adoptionValue like this :
if selectedAdoptionStatus in t["data-adoption-status"].split("|")
The following code lists all input tag and extracts the adoptionStatus for each one of these, it prompts user to choose a filter (0 to 4) and gets the selected countries by filtering on the data-adoption-status attribute :
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.ifrs.org/use-around-the-world/use-of-ifrs-standards-by-jurisdiction/")
soup = BeautifulSoup(r.text, "html.parser")
choiceContainer = soup.find("div", {"class":"map-filters"})
choices = [
(t["title"], t["value"])
for t in choiceContainer.findAll("input")
]
for idx, choice in enumerate(choices):
print(f"[{idx}] {choice[0]}")
val = input("Choose a filter index : ")
choice = choices[int(val)]
print(f"You have chosen {choice[0]}")
selectedAdoptionStatus = choice[1]
countryList = soup.find("div", {"id":"countries_list"})
selectedCountries = [
{
"countryCode": t["data-country-code"],
"adoptionStatus": t["data-adoption-status"].split("|"),
"link": t["href"],
"country": t.find("img")["alt"]
}
for t in countryList.findAll("a")
if selectedAdoptionStatus in t["data-adoption-status"].split("|")
]
for it in selectedCountries:
print(it["country"])
run this code on repl.it
Sample output
[0] IFRS Standards are required for use by all or most domestic publicly accountable entities.
[1] IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions.
[2] IFRS Standards are required or permitted for use by foreign securities issuers.
[3] In most cases an SME may also choose full IFRS Standards. In some cases, an SME may also choose local standards for SMEs.
[4] The body with authority to adopt financial reporting standards is actively studying whether to adopt the <em>IFRS for SMEs</em> Standard.
Choose a filter index : 1
You have chosen IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions.
Bermuda
Cayman Islands
Guatemala
Iraq
Japan
Madagascar
Nicaragua
Panama
Paraguay
Suriname
Switzerland
Timor-Leste

Showing JSON file into HTML

Hy everyone. I've been trying to import my JSON to HTML and make it into a table. My JSON contains:
{
"cover_title": "Haikyuu!! TO THE TOP",
"cover_studio": "Production I.G",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx106625-UR22wB2NuNVi.png",
"format": "TV",
"duration": "84%",
"description": "The fourth season of Haikyuu!!\n\nThe Karasuno High School Volleyball Club finally won their way into the nationals after an intense battle for the Miyagi Prefecture Spring Tournament qualifiers. As they were preparing for the nationals, Kageyama is invited to go to All-Japan Youth Training Camp. At the same time, Tsukishima is invited to go to a special rookie select training camp for first-years in Miyagi Prefecture. Hinata feels panic that he\u2019s being left behind as one of the first-years and then decides to show up at the Miyagi Prefecture rookie select training camp anyway...\n\n(Source: Crunchyroll)",
"genres": [
"Comedy ",
" Drama ",
" Sports"
]
},
{
"cover_title": "Eizouken ni wa Te wo Dasu na!",
"cover_studio": "Science SARU",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx109298-YvjfI88hX76T.png",
"format": "TV",
"duration": "79%",
"description": "First year high schooler Midori Asakusa loves anime so much, she insists that \"concept is everything\" in animation. Though she draws a variety of ideas in her sketchbook, she hasn't taken the first step to creating anime, insisting that she can't do it alone. The producer-type Sayaka Kanamori is the first to notice Asakusa's genius. Then, when it becomes clear that their classmate, charismatic fashion model Tsubame Mizusaki, really wants to be an animator, they create an animation club to realize the \"ultimate world\" that exists in their minds.\n\n(Source: Crunchyroll)",
"genres": [
"Adventure ",
" Comedy"
]
},
and my html is (i got this way from my friend but i dont think this works on my case):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"> </script>
<script>
$(function(){
$.get('anime.json', function(obj){
var str = "";
str+="<table border = '1'><tr><th>No</th><th>Judul</th></tr>";
$.each(obj, function(n,data){
str+="<tr><td>"+(n+1)+"</td>";
str+= "<td>"+data.cover_title+"</td></tr>";
});
$('#media').html(str);
});
});
</script>
</head>
<body>
<div id = "media"></div>
</body>
</html>
I've also try another ways from youtube, but it's still not working. What can I do? Thankyou.
jQuery Get function tries to automatically parse the json string and convert it to an array but when it encounters an internal error the success callback won't run.
Your json format doesn't look valid, you can confirm using this
$.get('a.json', function(obj){
var str = "";
str+="<table border = '1'><tr><th>No</th><th>Judul</th></tr>";
$.each(obj, function(n,data){
str+="<tr><td>"+(n+1)+"</td>";
str+= "<td>"+data.cover_title+"</td></tr>";
});
$('#media').html(str);
})
.catch( function(e){
alert('Error');
});
Your should correct it like
[{
"cover_title": "Haikyuu!! TO THE TOP",
"cover_studio": "Production I.G",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx106625-UR22wB2NuNVi.png",
"format": "TV",
"duration": "84%",
"description": "The fourth season of Haikyuu!!\n\nThe Karasuno High School Volleyball Club finally won their way into the nationals after an intense battle for the Miyagi Prefecture Spring Tournament qualifiers. As they were preparing for the nationals, Kageyama is invited to go to All-Japan Youth Training Camp. At the same time, Tsukishima is invited to go to a special rookie select training camp for first-years in Miyagi Prefecture. Hinata feels panic that he\u2019s being left behind as one of the first-years and then decides to show up at the Miyagi Prefecture rookie select training camp anyway...\n\n(Source: Crunchyroll)",
"genres": [
"Comedy ",
" Drama ",
" Sports"
]
},
{
"cover_title": "Eizouken ni wa Te wo Dasu na!",
"cover_studio": "Science SARU",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx109298-YvjfI88hX76T.png",
"format": "TV",
"duration": "79%",
"description": "First year high schooler Midori Asakusa loves anime so much, she insists that \"concept is everything\" in animation. Though she draws a variety of ideas in her sketchbook, she hasn't taken the first step to creating anime, insisting that she can't do it alone. The producer-type Sayaka Kanamori is the first to notice Asakusa's genius. Then, when it becomes clear that their classmate, charismatic fashion model Tsubame Mizusaki, really wants to be an animator, they create an animation club to realize the \"ultimate world\" that exists in their minds.\n\n(Source: Crunchyroll)",
"genres": [
"Adventure ",
" Comedy"
]
}]

xml tag replace showing different result

I wrote a function in one of my angular project to replace tag with another tag in xml file. First parameter is the HTMLElement, second parameter is the searchTag and third one is replaceTag.
replaceTagWith(xmlCode: HTMLElement, findTag: string, replaceTag: string) {
// Initializing variables
let exists: boolean = true;
let processed: boolean = false;
while (exists) {
let sourceTags = xmlCode.querySelector(findTag);
// If findTag exists
if (sourceTags) {
// Setting processed flag
processed = true;
// Creating replace tag and setting the textcontent
let targetTag = document.createElement(replaceTag);
targetTag.innerHTML = sourceTags.innerHTML;
// Finding attributes of the tags to be replaced
let tagAttributes = sourceTags.attributes;
let attrLength = tagAttributes.length;
// If there is attributes
if (attrLength) {
for (let j = 0; j < attrLength; j++) {
// Setting the attribute of replace tag
targetTag.setAttribute(tagAttributes[j].name, tagAttributes[j].value);
}
}
// Appending the target tag just before the source tag
sourceTags.parentNode.insertBefore(targetTag, sourceTags);
// Removing findTag
sourceTags.parentNode.removeChild(sourceTags);
} else {
exists = false;
}
}
This function works well when i am replacing <title> tag with <sec-title>. Here is the function call..
const parser = new DOMParser();
const xml = parser.parseFromString(this.xmlData, 'application/xml');
let xmlCode: any = xml.documentElement;
this.replaceTagWith(xmlCode, 'title', 'sec-title');
the result will be like:
<sec-title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </sec-title>
But the problem is that when i try to replace <sec-title> with <title> ,the result showing:
<title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </title>
the html tags (here <named-content>) inside the <title> get replaced with <named-content>
This is the portion of xml I am working with..
<sec level="2" id="sec002" sec-type="level-B">
<title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content content-type="index"
name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level=""
format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </title>
<p specific-use="para">Child protection is the ‘prevention of and response to abuse, neglect, exploitation and
violence against children’.</p>
<p specific-use="para">The objectives of humanitarian action are to:</p>
<list list-type="bullet" specific-use="1" list-content="Lijstalinea">
<list-item>
<p specific-use="para">Save lives, alleviate suffering and maintain human dignity during and after
disasters; and</p>
</list-item>
<list-item>
<p specific-use="para">Strengthen preparedness for any future crises.</p>
</list-item>
</list>
<p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
content-type="index" name="default" a-level="humanitarian crises" b-level="causes of" c-level=""
d-level="" e-level="" format="" range="" see="" see-also=""></named-content> can be caused by humans,
such as conflict or civil unrest; they can result from disasters, such as floods and earthquakes; or they
can be a combination of both.</p>
<p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
content-type="index" name="default" a-level="humanitarian crises" b-level="effects on children of"
c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content>
often have long-lasting, devastating effects on children’s lives. The child protection risks children face
include family separation, recruitment into armed forces or groups, physical or sexual abuse, psychosocial
distress or mental disorders, economic exploitation, injury and even death. They depend on factors such as
the:</p>
<list list-type="bullet" specific-use="1" list-content="Lijstalinea">
<list-item>
<p specific-use="para">Nature and scale of the emergency;</p>
</list-item>
<list-item>
<p specific-use="para">Number of children affected;</p>
</list-item>
<list-item>
<p specific-use="para">Sociocultural norms;</p>
</list-item>
<list-item>
<p specific-use="para">Pre-existing child protection risks;</p>
</list-item>
<list-item>
<p specific-use="para">Community-level preparedness; and</p>
</list-item>
<list-item>
<p specific-use="para">Stability and capacity of the State before and during the crisis.</p>
</list-item>
</list>
<p specific-use="para">Child protection actors and interventions seek to prevent and respond to all forms of
abuse, neglect, exploitation and violence. Effective child protection builds on existing capacities and
strengthens preparedness before a crisis occurs. During humanitarian crises, timely interventions support
the physical and emotional health, dignity and well-being of children, families and communities.</p>
<p specific-use="para">Child protection in humanitarian action includes specific activities conducted by local,
national and international child protection actors. It also includes efforts of non-child protection actors
who seek to prevent and address abuse, neglect, exploitation and violence against children in humanitarian
settings, whether through mainstreamed or integrated programming.</p>
<p specific-use="para">Child Protection in Humanitarian Action promotes the well-being and healthy development
of children and saves lives.</p>
</sec>
To display this code in broser i first replaced the <title> tag with <sec-title> and it works fine. Finally at the stage of exporting xml i replaced back <sec-title> with <title>. Here is the stage where the problem occurring...

How do I maintain the same JSON format from web API response after an AJAX call?

I have a web API that returns the following JSON:
[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]
I want to pass JSON from the response to jqGrid to populate the data in a table, after my AJAX call which looks as follows:
function fetchMovies(){
$.ajax({
url: 'http://orionadmin.azurewebsites.net/api/movies',
type: 'GET',
datatype: 'JSON',
contentType: 'application/json',
success: function (data) {
grid_data1 = JSON.stringify(data);
alert(grid_data);
},
error: function (x, h, r) {
alert('Something went wrong')
}
});
}
My result from the AJAX call looks as follows:
"[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]"
This is the format jqGrid takes, to populate data in the table:
<script type="text/javascript">
var grid_data =
[
{id:"1",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"2",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"3",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"4",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"5",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
{id:"6",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"7",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"8",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"9",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"10",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"11",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"12",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"13",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"14",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
{id:"15",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"16",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"17",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"18",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"19",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"20",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"21",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"22",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"23",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}
];
How do I maintain the original JSON format without the " " after the AJAX call, so that I can get my data displayed in my jqGrid?
Maybe something like this?
'[{"MovieId":2,"Title":"End Game","Year"...'.replace(new RegExp('"', 'g'), '')
You don't need JSON.stringify(), your data is already in json format
JSON is basically a format where you pass Javascript as a string. JQuery actually parses the string into an object, which is what you want. But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object.
TL;DR: Don't stringify it
You can use addRowData method of JqGrid. it expects an object as input, since your result is an array of objects you just need to loop through the array and add Row Data
var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"},{"MovieId":4,"Title":"Cobra","Year":"1986","Actors":"Sylvester Stallone, Brigitte Nielsen, Reni Santoni, Andrew Robinson","Plot":"A tough-on-crime street cop must protect the only surviving witness to a strange murderous cult with far reaching plans","Director":"George P. Cosmatos","Cover":"cobra.jpg"},{"MovieId":5,"Title":"Savages","Year":"2012","Actors":"Blake Lively, Taylor Kitsch, Aaron Taylor-Johnson, Jana Banker","Plot":"Pot growers Ben and Chon face off against the Mexican drug cartel who kidnapped their shared girlfriend","Director":"Oliver Stone","Cover":"savages.jpg"},{"MovieId":6,"Title":"The Man in the Iron Mask","Year":"1998","Actors":"Leonardo DiCaprio, Jeremy Irons, John Malkovich, Gérard Depardieu","Plot":"The cruel King Louis XIV of France has a secret twin brother who he keeps imprisoned. Can the twin be substituted for the real king?\"","Director":"Randall Wallac","Cover":"maninimask.jpg"},{"MovieId":7,"Title":"The Shawshank Redemption","Year":"1994","Actors":"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","Plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","Director":"Frank Darabont","Cover":"MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_SX300.jpg"},{"MovieId":8,"Title":"Perfume: The Story of a Murderer","Year":"2006","Actors":"Ben Whishaw, Francesc Albiol, Gonzalo Cunill, Roger Salvany","Plot":"Jean-Baptiste Grenouille, born with a superior olfactory sense, creates the world's finest perfume. His work, however, takes a dark turn as he searches for the ultimate scent.","Director":"Tom Tykwer","Cover":"MV5BMTI0NjUyMTk3Nl5BMl5BanBnXkFtZTcwOTA5MzkzMQ##._V1_SX300.jpg"},{"MovieId":9,"Title":"Catch Me If You Can","Year":"2002","Actors":"Leonardo DiCaprio, Tom Hanks, Christopher Walken, Martin Sheen","Plot":"The true story of Frank Abagnale Jr. who, before his 19th birthday, successfully conned millions of dollars' worth of checks as a Pan Am pilot, doctor, and legal prosecutor.","Director":"Steven Spielberg","Cover":"MV5BMTY5MzYzNjc5NV5BMl5BanBnXkFtZTYwNTUyNTc2._V1_SX300.jpg"},{"MovieId":10,"Title":"James Bond 007","Year":"2003","Actors":"Pierce Brosnan, John Cleese, Willem Dafoe, Judi Dench","Plot":"MI6 agent James Bond:007 rushes into action to rescue Oxford scientist Katya Nadanova from a terrorist facility in Egypt. After rescuing Katya bond heads to a mining town in Peru to ..","Director":"Scot Bayless","Cover":"007.jpg"},{"MovieId":11,"Title":"The Mask","Year":"1994","Actors":"Jim Carrey, Peter Riegert, Peter Greene, Amy Yasbeck","Plot":"Bank clerk Stanley Ipkiss is transformed into a manic superhero when he wears a mysterious mas","Director":"Chuck Russel","Cover":"theMask.jpg"},{"MovieId":12,"Title":"Rambo","Year":"2008","Actors":"Sylvester Stallone, Julie Benz, Matthew Marsden, Graham McTavish","Plot":"In Thailand, John Rambo joins a group of missionaries to venture into war-torn Burma, and rescue a group of Christian aid workers who were kidnapped by the ruthless local infantry unit","Director":"Sylvester Stallone","Cover":"rambo.jpg"},{"MovieId":13,"Title":"The Green Mile","Year":"1999","Actors":"Tom Hanks, David Morse, Michael Clarke Duncan, Bonnie Hunt\",\"Plot\":\"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift","Plot":"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift.\",\"Language\":\"English, French\",\"Country\":\"USA\",\"Awards\":\"Nominated for 4 Oscars. Another 15 wins & 30 nominations","Director":"Frank Darabont","Cover":"greenmile.jpg"}]
$("#grid").jqGrid({
datatype: "local",
height: 250,
colNames: ['MovieId', 'Title', 'Title', 'Actors', 'Plot','Director'],
colModel: [{
name: 'MovieId',
index: 'MovieId',
width: 60,
search:false},
{
name: 'Title',
index: 'Title',
width: 120,
search:false},
{
name: 'Year',
index: 'Year',
width: 60,
search:false},
{
name: 'Actors',
index: 'Actors',
width: 120,
search:false},
{
name: 'Plot',
index: 'Plot',
width: 120,
search:false},
{
name: 'Director',
index: 'Director',
width: 120,
search:false}
],
caption: "IMDB"
});
for (var i = 0; i <= data.length; i++) {
$("#grid").jqGrid('addRowData', i + 1, data[i]);
}
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script>
<table id="grid"></table>

How can I use jquery (or other javascript) to parse data from iTunes-formatted podcast XML feed?

I found the demo at think2loud.com that shows how to use jquery to parse an XML file. I have downloaded the source files and uploaded them to my own server and it works fine. A soon as I try to apply it to my own xml file (iTunes podcast feed) I don't get any output. I'm kind of in over my head, I think.
What I'd like is to have ONLY THE FIRST podcast info displayed in the following format:
< a href = path to file . mp3 > Title of message< / a >
Description of message
where:
GUID is path to file
TITLE is Title of Message
ITUNES:SUBTITLE is Description of message
Here's a sample of the demo code I'd like to tweak:
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "sites.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('site').each(function(){
var id = $(this).attr('id');
var title = $(this).find('title').text();
var url = $(this).find('url').text();
$('<div class="items" id="link_'+id+'"></div>').html(''+title+'').appendTo('#page-wrap');
$(this).find('desc').each(function(){
var brief = $(this).find('brief').text();
var long = $(this).find('long').text();
$('<div class="brief"></div>').html(brief).appendTo('#link_'+id);
$('<div class="long"></div>').html(long).appendTo('#link_'+id);
});
});
}
});
});
</script>
and here's an excerpt of the XML file I'd like to parse:
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link rel="self" type="application/rss+xml" href="http://www.deepwaterchurch.com/podcast/podcast.xml" />
<lastBuildDate>Mon, 15 Aug 2011 13:30:32 -0300</lastBuildDate>
<title>Deep Water Podcast</title>
<itunes:author>AJ Thomas</itunes:author>
<link>http://www.deepwaterchurch.com</link>
<generator>Podcast Maker v1.4.1 - http://www.lemonzdream.com/podcastmaker</generator>
<description><![CDATA[The weekly message from Deep Water Church in Halifax, Nova Scotia.]]></description>
<itunes:subtitle />
<itunes:summary>The weekly message from Deep Water Church in Halifax, Nova Scotia.</itunes:summary>
<language>en</language>
<copyright>2007 Deep Water Church</copyright>
<image>
<url>http://www.deepwaterchurch.com/podcast/podcast_144.jpg</url>
<title>Deep Water Podcast</title>
<link>http://www.deepwaterchurch.com</link>
<width>144</width>
<height>144</height>
</image>
<itunes:image href="http://www.deepwaterchurch.com/podcast/podcast.jpg" />
<category>Christianity</category>
<itunes:category text="Religion & Spirituality">
<itunes:category text="Christianity" />
</itunes:category>
<category>Spirituality</category>
<itunes:category text="Religion & Spirituality">
<itunes:category text="Spirituality" />
</itunes:category>
<category>Non-Profit</category>
<itunes:category text="Government & Organizations">
<itunes:category text="Non-Profit" />
</itunes:category>
<itunes:keywords>deep water, deepwater, church, halifax, nova scotia, canada, jesus, aj thomas</itunes:keywords>
<itunes:explicit>no</itunes:explicit>
<item>
<title>Hurry Up and Wait - Slow Down</title>
<itunes:author>Deep Water</itunes:author>
<description><![CDATA[Episode 2 of 2. Luke 10:38-42. A life that is ministry isn't just about being busy all the time-- we need to take time to sit at Jesus' feet and be quiet, too.]]></description>
<itunes:subtitle>Episode 2 of 2. Luke 10:38-42. A life that is ministry isn&apos;t just about being busy all the time-- we need to take time to sit at Jesus&apos; feet and be quiet, too.</itunes:subtitle>
<itunes:summary />
<enclosure url="http://www.deepwaterchurch.com/podcast/Jen%20Ochej-August%2014%2C%202011.mp3" type="audio/mpeg" length="16625879" />
<guid>http://www.deepwaterchurch.com/podcast/Jen%20Ochej-August%2014%2C%202011.mp3</guid>
<pubDate>Mon, 15 Aug 2011 13:29:03 -0300</pubDate>
<category>Christianity</category>
<itunes:explicit>no</itunes:explicit>
<itunes:duration>00:34:34</itunes:duration>
<itunes:keywords>deep water, deepwater, church, halifax, nova scotia, canada, jesus, aj thomas</itunes:keywords>
</item>
The link to the demo I've been playing with is here
Like I mentioned, I'd like this to pull only the most recently updated podcast (first "item") from the list. I'm clearly in over my head! I'd appreciate some guidance. Thanks tons.
Ok, I've got it working... kind of. I have it appending to the "body", but I'd like to assign it to a specific DIV, like the original example. When I try to set the link.appendTo('body'); to link.appendTo('podcast'); I get no output. EDIT: I figured that part out. Still need help with the next question, though.
Secondarily, I'd like to be able to have a description of the episode ("itunes:subtitle" in the XML file) placed under the link. Can we make this happen?
Give it a try:
jQuery(
function($)
{
$.get('sites.xml',
function(xml)
{
var item=$('channel > item:first',xml);
if(item.length)
{
var link=$('<a/>').attr('href',$('enclosure',item).attr('url'))
.text($('title',item).text());
//put it where you want to
link.appendTo('body');
}
},
'xml')
}
);
Returns for me right now for http://www.deepwaterchurch.com/podcast/podcast.xml
Hurry Up and Wait - Slow Down

Categories