Read xml in browser - javascript

I have below string in javascript
var output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><abc><xyz><xyzResponse><URL>http%3A%2F%2Flocalhost%3A8080%2Fnet%2Fxyz.do%3Fpartner%3Ddummy%26id%3Dba0e245f-ae67-40b6-986d-3242acea4c04</URL><StatusMsg>SUCCESS</StatusMsg><ID>hello.com</ID><AID>test</AID></xyzResponse></xyz></abc>';
I want to parse this as xml and get values out of it.
I have tried below code
var xmlObj = $(output);
alert(xmlObj.find('URL').text())
It works in FireFox but does not work in IE. It does not give any error but does not show any content.
How to read xml that is string format and use content using javascript across the browsers?
Any help is appreciated.

jQuery's $() function doesn't parse XML: it treats it as HTML and inserts it into the HTML DOM, which doesn't work in general. If you're using jQuery 1.5, you can use its new parseXML() method:
var xmlObj = $.parseXML(output);
alert( $(xmlObj).find('URL').text() );
If you can't use jQuery 1.5, you'll need an XML parsing function such as the one I posted here: Strange jQuery XML problem

I did the following for parsing xml for all browsers. I hope you will find it helpful too.
if(window.DOMParser)//Firefox, Chrome and others Browsers
{
var xmlString = (new XMLSerializer()).serializeToString(response);
parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlString,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load(response);
}

Related

how to get xml namespace in javascript

my xml is
<message to="to_test" from="from_test">
<test xmlns="google:mobile:data">
{"message":"test_message"}
</test>
</message>
i get the value {"message":"test_message"} by using the function getChildText("pcm"). But i tried to retrieve the namespace xmlns value.
I tried the following How to get XML namespace? , How to get specific XML namespace in XQuery in SQL Server with no luck, it shows me is not function error what i'm doing wrong?
I forgot to mention, I'm currently staring work with node.js.
update
the above xml output is xmpp stanza.
Here i'm getting the attrs using the following.
stanza.attrs.to gives me to_test.
stanza.attrs.from gives me from_test.
stanza.getChildText("test") gives me {"message":"test_message"}
I tried to get the xmlns using
var parser = new DOMParser();
var documents = parser.parseFromString(stanza, 'text/xml');
var response = documents.responseXML.getElementsByTagName("test");
var sunrise = response[0].getElementsByTagNameNS("[Namespace URI]", "test")[0].getAttribute("xmlns");
console.log(sunrise);
here i got
[xmldom error] element parse error: TypeError: source.indexOf is not a function ##[line:0,col:undefined]
Using the standard browser's DOM parser, you can do the following:
var txt = "<message><test xmlns=\"google:mobile:data\"> {\"message\":\"test_message\"}</test></message>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");
ns = xmlDoc.getElementsByTagName("test")[0].namespaceURI
I have tested with Chrome and IE and it works.
I hit a similar error -- in my case it was because I had passed something besides a string to "parseFromString". Could this be the problem? It looks like "stanza" is not a string.

Internet Explorer 8 parse XML doesn`t work on huge response size

I have a huge page with really lots of data. Sometimes I need to reload this data using Ajax, so ajax request:
if (window.XMLHttpRequest) {
this._request = new XMLHttpRequest();
} else {
this._request = new ActiveXObject("Microsoft.XMLHTTP");
Then, I access this data with request.responseXML. I faced a problem, when size of responsibility more than 800k characters.
IE doesnt generate responseXML, its just empty XMLObject, but in responseText everithing is OK. I`ve tried to parse XML using the following code:
if (request.responseXML) {
var responseXML = request.responseXML;
//TODO: for huge xml responses some versions of IE can't automaticly parse XML
if (O$.isExplorer && responseXML && !responseXML.firstChild) {
var originalResponseText = request.responseText;
if (window.DOMParser) {
var parser = new DOMParser();
responseXML = parser.parseFromString(originalResponseText, 'text/xml');
} else {
responseXML = new ActiveXObject("Microsoft.XMLDOM");
responseXML.async = false;
responseXML.loadXML(originalResponseText);
}
}
But I faced the same problem.
Then, I tried to parse XML using jQuery:
responseXML = jQuery.parseXml(request.responseXML);
But the problem is still the same, everything is fine when the response length small, but for huge response I still get empty XML object with the parse error inside.
errorCode : -2147467259
filepos : 814853
reason : “Unspecified error\r\n”;
I check those position inside response string and everything is correct, just some ordinal symbol. Also I’ve recheck XML lots of time and I am sure that it’s valid. I don’t know what to do at all.
Also I tried to write my own xml parser, but I think that this is problem has more simple solution.
Thanks in Advance.
It would seem that IE notoriously has difficulties parsing XML data, and there may not be that much you can really do about it. A work around is that you can try to parse the XML data with IE, and if it fails, construct a new parser that will construct XML data out of the plaintext (which as you mentioned will work seemingly regardless of size). Take a look at the similar problem and answer here. It boils down to (pseudocode)
function() {
var XMLdata = reponse.XMLdata;
If (XMLdata.error) {
var parser = construct new DOMParser;
XMLdata = parser.XMLparse(response.plaintext);
}
return XMLdata;
}

Loading local XML in IE

Im trying to read a local xml file without using active-x in IE based on code from this site
var xml = document.createElement("xml");
xml.src = 'file.xml';
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
console.log(xml.XMLDocument); //undefined
console.log(xml); //<xml XMLDocument="[object]">
What I need here is the [object] that contains my XML file. But I can't manage to fetch it (see above). Did I miss something obvious?
To anyone who runs in to this problem: The XMLDocument property doesn't exist in IE9, therefore causing the issue.

Simplest possible method: html break in XML doc

I have a c program which outputs a number of lines to another c program which stuffs them in a PHP page which is loaded with AJAX. The problem is that the output is a number of lines, which is fine to look at, but which, when viewed as HTML, lack line breaks.
The initial thought I had was obviously to put line breaks in with the output. -- That worked fine, especially since I was using responseText to handle the AJAX output. Now I have discovered that along with the raw text, a bit of metadata also needs to be part of the AJAX response. I jumped over to using responseXML, only to find that the tags no longer worked correctly. At this point I could slog through any number of tutorials to figure out how to work some more complicated mechanism, but I really just want a hack. Could I embed the metadata in an html comment and use the DOM to dig it out (I looked and don't see a good method to get to comments using the dom...)? Could I use the xml directly as html somehow? Could I use CDATA in the xml document(this doesn't seem hopeful)? Could I just use newlines until the code reaches the webpage and then have JS insert the br tags?
I don't need any other formatting, just line breaks, and all this needs to do is work, the less complex the better.
How about using a XSLT stylesheet to format your incoming XML. Save the following as an .html file for an example. Sources : http://www.w3schools.com/xsl/xsl_client.asp & http://www.w3schools.com/dom/dom_parser.asp
<html>
<head>
<script>
//YOUR XML FROM AJAX
var XML = "<top><meta><itemone>test meta</itemone></meta><rows><row>line one</row><row>line two</row><row>line three</row></rows></top>";
//A stylesheet to format the lines that come back.
var XSLT = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"><h2>Lines</h2><xsl:for-each select="descendant::row"><xsl:value-of select="self::*"/><br /></xsl:for-each></xsl:template></xsl:stylesheet>'
function loadXMLDoc(xml)
{
var tempXML;
//IE
if (window.ActiveXObject)
{
tempXML=new ActiveXObject("Microsoft.XMLDOM");
tempXML.loadXML(xml);
}
else if(window.DOMParser)
{
parser=new DOMParser();
tempXML=parser.parseFromString(xml,"text/xml");
}
return tempXML;
}
function displayResult()
{
var xmlDoc = loadXMLDoc(XML);
var xsltDoc = loadXMLDoc(XSLT);
// code for IE
if (window.ActiveXObject)
{
var ex=xmlDoc.transformNode(xsltDoc);
document.getElementById("example").innerHTML=ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
var xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
var resultDocument = xsltProcessor.transformToFragment(xmlDoc,document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
Thanks for all the good suggestions, but I eventually decided to just prepend a fixed number of descriptor bytes to each text response and then use the substring command to get either the descriptor bytes or the main text response.
This allows me to keep using the simpler response-text mechanism, and is otherwise uncomplicated.
I would have used custom headers but I realized that that would have required buffering the whole output in yet ANOTHER place since the php script actually only contains a single system() call, and has no idea what the C program behind it is doing.

Loading a xml to a class with Javascript

How can I load a XML file to class using Javascript?
Unfortunately, each browser presents its own way of parsing a string containing XML. Here are the ways that I know of for each of the big 3 browsers. Please note, I haven't had a chance to try each of these as they're cobbled together from various blogs and my own memory.
Firefox has an object called DOMParser that can be used to parse XML in a string. The API is pretty simple -- instantiate the DOMParser and call its parseFromString method. Here is an example:
var xmlString = '<?xml version="1.0"?>...';
var parser = new DOMParser();
var dom = parser.parseFromString(theString, "text/xml");
// use dom
IE uses the Microsoft ActiveX XMLDOM control, therefore you must instantiate the DOM control and use its methods, again here's an example:
var xmlString = '<?xml version="1.0"?>...';
dom=new ActiveXObject("Microsoft.XMLDOM");
dom.async="false";
dom.loadXML(xmlString);
// use dom
And lastly, the weirdo Safari version. Safari doesn't have a parser built in, and being that it doesn't run on Windows it doesn't support ActiveX controls. However, Safari does support data: urls. In Safari a URL with the document is created and called through an XMLHTTPRequest. Like all XMLHttpRequests, you use the standard responseXml property of the XMLHttpRequest to access the DOM.
var xmlString = '<?xml version="1.0"?>...';
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(xmlString);
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);
var dom = xhr.responseXML;
// Use dom here
I'm not aware of a built-in XML serializer/deserializer in JavaScript. Is you considered something native to JavaScript, like JSON?
Here is an XML to JSON Javascript converter that might steer you in the right direction.
This code will work for all kind of browsers
var url="file.xml"
var xmlDoc="";
if(window.XMLHttpRequest&&!window.ActiveXObject)
{
var Gz=new XMLHttpRequest();Gz.open('GET',url,false);Gz.send(null);xmlDoc=Gz.responseXML;
}
else
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.load(url);
}
After using this, you can parse the tag and retrieve the data.

Categories

Resources