how to get xml namespace in javascript - 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.

Related

xml2json.js error: Syntax error

I want to convert an XML file, after many trials with my AngularJS application, I've simply uploaded on the server the samples.html that I've found at https://github.com/abdmob/x2js .
The result is always the same: on the console I receive a "SCRIPTxxxx: Syntax error xml2json.min.js" and "SCRIPTxxxx: 'X2JS' is undefined". The script is linked normally, like:<script type="text/javascript" src="/vendor-scripts/xml2json.min.js"></script> (same issue with xml2json.js) and also this simple code gives the same error: var x2js = new X2JS();
var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
var jsonObj = x2js.xml_str2json( xmlText );. Does anyone know if this is a known issue (I didn't find anything on the net) or if there are other libraries to do this job?

How do I parse the attached XML code using JavaScript?

I have a requirement to read data from the XML file.
Here is the data in XML file.
<?xml version="1.0"?>
<application id="AndroidCoverFlow" name="AndroidCoverFlow" platform="general">
<attributes datatype="ref" value="{"coverflowConfig":{"spaceBetweenRowItems":5,"projectionAngle":90,"isCircular":true,"rowItemWidth":5,"rowItemRotationAngle":180}}" name="viewConfig" platform="general" buckettype="basic"/>
</application>
in the specified example, I want to verify/Read the coverflowconfig values.i.e
spaceBetweenRowItems,
projectionAngle
projectionAngle.
I hope this isn't the exact XML, because it's not valid. But forgetting that... assuming it is valid, you can parse it using DOMParser.
var parser = new DOMParser,
xmlDom = parser.parseFromString(xml, 'text/xml');
var application = xmlDom.getElementById('AndroidCoverFlow'),
attributes = application.getElementsByTagName('attributes');
var value = attributes[0].attributes.getNamedItem('value').value,
jsonData = JSON.parse(value);
console.dir(jsonData);
DEMO: http://jsbin.com/soxobuba/2/edit?js,console
Fiddle: http://jsfiddle.net/abdennour/MUws7/
NOTE:
It is not an XML code, You could check it By :
http://www.w3schools.com/xml/xml_validator.asp
However , if it is an XML Code , You can use a Javascript library such as jQuery, then do this :
$(xml).find("attributes").each(function()
{
var myObject=$(this).attr("value")
$("#output").html(myObject);
myObject=myObject.replaceAll("'",'"')
alert(myObject)
coverflowConfig=$.parseJSON(myObject).coverflowConfig;
alert('coverflowConfig.projectionAngle='+coverflowConfig.projectionAngle)
});
Fiddle: http://jsfiddle.net/abdennour/MUws7/

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.

modify xml using javascript

I am starting to learn xml and I am facing a problem. I need to add elements to the xml file so I use this method:
function newNode()
{
var xmlDoc = loadXMLDoc("Nodes.xml");
var nodes = xmlDoc.documentElement;
var newNode = xmlDoc.createElement('node');
var newName = xmlDoc.createElement('name');
var newText = xmlDoc.createTextNode('Start Node');
newName.appendChild(newText);
newNode.appendChild(newName);
xmlDoc.documentElement.appendChild(newNode);
alert(xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue);
return xmlDoc;
}
it works fine and the alert shows "Start Node", but when I use the same alert command as in:
function z()
{
var xmlDoc = loadXMLDoc("Nodes.xml");
alert(xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue);
}
I get this error: Unable to get value of the property 'childNodes': object is null or undefined.
Could you please send an example of XML file before running your z function ?
With what I can see here, it simply means that there is no "name" node in the document, meaning that getElementsByTagName("name") = [], explaining why getElementsByTagName("name")[0] is undefined.
I hate to be that guy, but XML can be easily modified and traversed using a library like jQuery, dojo, mootools, or my recent favorite zepto (if you don't need to support old IE).

Read xml in browser

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);
}

Categories

Resources