Reading xml using jquery or javascript - javascript

My xml looks like this, I am able to retrieve the items and get the data from nodes like <title>, <description>. How to get the values from <media:title> and <media:credit>, <media:thumbnail>
This is how am able to get the data
var xmlparser = new DOMParser();
var xmlData = xmlparser.parseFromString(data.text(), "text/xml");
var items = xmlData.getElementsByTagName('item');
for(var i = 0; i < items.length; i++){
var title = items[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var desc = items[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
}
<pre xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<Channel>
<item>
<title>List of records</title>
<description>reading xml</description.
<media:title xmlns:media="http://search.yahoo.com/mrss/">
SinkorSwim Trailer
</media:title>
<title>Sink or Swim - Trailer</title>
<description>Jon Bowermaster's documentary</description>
<media:description xmlns:media="http://search.yahoo.com/mrss/">
Jon Bowermaster's documentary on a learn-to-swim camp
</media:description>
<media:credit xmlns:media="http://search.yahoo.com/mrss/" role="Director"
scheme="urn:ebu">
Jon Bowermaster
</media:credit>
<media:status xmlns:media="http://search.yahoo.com/mrss/" state="active"/>
<media:thumbnail xmlns:media="http://search.yahoo.com/mrss/"
type="landscape" url="http://snagfilms-video.jpg"/>
<media:player xmlns:media="http://search.yahoo.com/mrss/" height="323"
url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-
affd-b32ce8700000" width="500"/>
</item>
<item></item>
<item></item>
</channel>
</pre>

The media in media:title denotes an XML namespace prefix. The namespace prefix is only a shortcut for the namespace. The namespace has to be defined somewhere in the document with an xmlns:media attribute.
Then you can use the namespace aware getElementsByTagNameNS() function to query for the title element:
console.log(xml.getElementsByTagNameNS('xmlns:media="http://search.yahoo.com/mrss/"', 'title'));
first parameter you have to pass the namespace name and not the prefix.

Related

Parse RSS <content:encoded> with native javaScript

I'm parsing a RSS feed which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:npr="http://www.npr.org/rss/" xmlns:nprml="http://api.npr.org/nprml" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
<channel>
<title>News</title>
<link>http://www.npr.org/templates/story/story.php?storyId=1001&ft=1&f=1001</link>
<description>NPR news, audio, and podcasts. Coverage of breaking stories, national and world news, politics, business, science, technology, and extended coverage of major national and world events.</description>
<language>en</language>
<copyright>Copyright 2012 NPR - For Personal Use Only</copyright>
<generator>NPR API RSS Generator 0.94</generator>
<lastBuildDate>Tue, 28 Aug 2012 12:19:00 -0400</lastBuildDate>
<image>
<url>http://media.npr.org/images/npr_news_123x20.gif</url>
<title>News</title>
<link>http://www.npr.org/templates/story/story.php?storyId=1001&ft=1&f=1001</link>
</image>
<item>
<title>Reports: Obama Administration Will Unveil New Fuel-Efficiency Standards</title>
<description>The new rules will require U.S. cars to average 54.5 miles per gallon by 2025.</description>
<pubDate>Tue, 28 Aug 2012 12:19:00 -0400</pubDate>
<link>http://www.npr.org/blogs/thetwo-way/2012/08/28/160172356/reports-obama-administration-will-unveil-new-fuel-efficiency-standards?ft=1&f=1001</link>
<guid>http://www.npr.org/blogs/thetwo-way/2012/08/28/160172356/reports-obama-administration-will-unveil-new-fuel-efficiency-standards?ft=1&f=1001</guid>
<content:encoded><![CDATA[<p>The new rules will require U.S. cars to average 54.5 miles per gallon by 2025.</p><p>» E-Mail This » Add to Del.icio.us</p>]]></content:encoded>
</item>
</channel>
</rss>
I'm looping the items like this:
var channel = xml.documentElement.getElementsByTagName("channel");
var items = xml.documentElement.getElementsByTagName("item");
for (var i = 0; i < items.length; i++) {
var ul = document.getElementById("feed");
var li = document.createElement('li');
var item = items.item(i);
var title = item.getElementsByTagName("title").item(0).textContent;
var link = item.getElementsByTagName("link").item(0).textContent;
var description = item.getElementsByTagName("link").item(0).textContent;
//var content = item.getElementsByTagName('content\\:encoded').item(0).textContent;
var li = document.createElement('li');
li.innerHTML = '' + title + '';
document.getElementById('feed').appendChild(li);
}
But how can I get the contents of the node <content:encoded>?
I tried with: item.getElementsByTagName('content\\:encoded').item(0).textContent; but it's not working.
Using jQuery this one inside .each() works: $(this).find('content\\:encoded').text(); but I'd rather use native javaScript.
So, it seems that I needed to use the tag getElementsByTagNameNS and that the node was "encoded" - like this:
var content = item.getElementsByTagNameNS("*", "encoded").item(0).textContent;
my solution:
var result2 = JSON.parse(result1);
setData(result2.rss.channel.item[0].["content:encoded"]);
jus use ["content:encoded"]

innerHTML missing when XML parsing with jQuery in IE9 but not Chrome

I'm using jQuery's XML parser on some simple content that contains HTML.
Extracting the full HTML text using jQuery's .html() or standard javascript .innerHTML works fine in Chrome, but not in Internet Explorer 9. jQuery's .text() works in both cases, but I need the html tags extracted as well.
How can I make it work with IE9 as well?
You can test it out here:
http://jsfiddle.net/199vLsgz/
XML:
<script id="xml_data" type="text/xml">
<model_data name="The model ">
<person_responsible></person_responsible>
<objects>
<object name="Available B reports" id="obj1" >
<description>this is a description <br/> oh look, another line!</description>
</object>
</objects>
</model_data>
</script>
Code:
$(function() {
var xml = $("#xml_data").text();
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
alert(desc.html());
})
Xml elements do not have innerHTML defined inside IE which is what's being used with the html function of jquery.
Firstly you need to use CDATA to preserve tags inside xml tags
<description><![CDATA[this is a description <br/> oh look, another line!]]></description>
then you can try to use the textContent property:
alert(desc[0].textContent); //desc.text() will also work now
And you also can add the content correctly using something like:
$('#some-container').html(desc[0].textContent);
$(function() {
var xml = $("#xml_data").text();
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
console.log($xml)
var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
alert(desc[0].textContent);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script id="xml_data" type="text/xml">
<model_data name="The model">
<person_responsible></person_responsible>
<objects>
<object name="Available B reports" id="obj1" >
<description><![CDATA[this is a description <br/> oh look, another line!]]></description>
</object>
</objects>
</model_data>
</script>

how to Convert a var to xml content using jquery

I am currently working with Jquery and my entire project needs to be done only using sharepoint Client Object Model (so i cant make use of server side coding). I have created a xml structure (by appending some string together) and stored it in a jquery var variable. Now my variable content looks like this
<Collection xmlns="http://schemas.microsoft.com/collection/metadata/2009"
xmlns:ui="http://schemas.microsoft.com/livelabs/pivot/collection/2009"
SchemaVersion="1" Name="listname">
<FacetCategories>
<FacetCategory Name="Title" Type="String" />
<FacetCategory Name="Created By" Type="String" />
<FacetCategory Name="Modified By" Type="String" />
</FacetCategories>
<Items ImgBase="http://460d87.dzc">
<Item Id="0" Img="#0" Name="Name1" Href="http://site/1_.000">
<Facets>
<Facet Name="Title">
<String Value="Name1" />
</Facet>
</Facets>
</Item>
</Items>
</collection>
I want to convert this variable in to xml content purely based on jquery.I have used ParseXml() Method but i'm not able to see the output in alert(). Please help me out with this.
Just use native built-in XML parser:
var parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
}
var nodes = xml.getElementsByTagName('FacetCategory');
var i, l = nodes.length, items = [];
for (i = 0; i < l; i++) {
console.log(nodes[i].getAttribute('Name'));
}
http://jsfiddle.net/QqtMa/
Your xml is invalid, your root element is Collection but the closing tag is collection with small c, so the parser is failing

Create XML in JavaScript

Is it possible to create an XML file with some data in JavaScript? I have the data stored in variables.
I've googled around a bit and it doesn't seem like it's talked about much. I thought I could use XMLWriter such as this:
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
as stated in this tutorial: EHow Tutorial
However, when I execute this code, I get the following error:
ReferenceError: XMLWriter is not defined
How can I solve this error?
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
JavaScript handles XML with 'XML DOM objects'.
You can obtain such an object in three ways:
1. Creating a new XML DOM object
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3. Parsing a string containing serialized XML
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
Note:
It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
Consider that we need to create the following XML document:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
Example
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
xml-writer(npm package)
I think this is the good way to create and write xml file easy.
Also it can be used on server side with nodejs.
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());
Simply use
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
this work for me..
var xml = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");
developer.mozilla.org/en-US/docs/Web/API/DOMParser
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
Your code is referencing this library
You can include it, and then your code in question should run as is. If you want to do this without prepending the library & build it with builtin functions only - follow answer from #Seb3736.
In Browser Example
<html>
<head>
<script src="Global.js" language="javascript"></script>
<script src="XMLWriter.js" language="javascript"></script>
<script language="javascript" type="text/javascript">
function genXML(){
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
//Do something... eg.
console.log(XML.ToString); //Yes ToString() not toString()
}
</script>
</head>
<body>
<input type="submit" value="genXML" onclick="genXML();">
</body>
</html>

Attributes of XML node using Javascript

Is there a way to get the name of an attribute of an XML node using javascript.
Lets take this as a sample XML
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Count name="EmployeeCount">100</Count>
<employee id="9999" >Harish</employee>
<Salary>
<year id="2000">50 Grands</year>
<year id="2001">75 Grands</year>
<year id="2002">100 Grands</year>
</Salary>
</Employees>
I am loading XML using ActiveXObject.As you can see not all elements have attributes.I need to list all attributes like
name
id
id
id
id
Try this:
var nodes = xml.selectNodes("//#*")
for(var i=0; i < nodes.length; i++)
{
alert(nodes[i].nodeName);
}

Categories