How do I parse the attached XML code using JavaScript? - 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/

Related

How Edit data of an XML node with Javascript

I want to write some data in an existing local XML file with Javascript with some text from an Html page. Is it possible to change content of nodes?
Here is XML sample:
<Notepad>
<Name>Player1</Name>
<Notes>text1</Notes>
</Notepad>
I will get some more text from input and want to add it after "text1", but can't find a solution.
function SaveNotes(content,player)
{
var xml = "serialize.xml";
var xmlTree = parseXml("<Notepad></Notepad>");
var str = xmlTree.createElement("Notes");
$(xmlTree).find("Notepad").find(player).append(str);
$(xmlTree).find("Notes").find(player).append(content);
var xmlString = (new XMLSerializer()).serializeToString(xmlTree);
}
Here is the code to manipulate xml content or xml file :
[Update]
Please check this Fiddle
var parseXml;
parseXml = function(xmlStr) {
return (new window.DOMParser()).parseFromString(xmlStr, "text/xml");
};
var xmlTree = parseXml("<root></root>");
function add_children(child_name, parent_name) {
str = xmlTree.createElement(child_name);
//strXML = parseXml(str);
$(xmlTree).find(parent_name).append(str);
$(xmlTree).find(child_name).append("hello");
var xmlString = (new XMLSerializer()).serializeToString(xmlTree);
alert(xmlString);
}
add_children("apple", "root");
add_children("orange", "root");
add_children("lychee", "root");
you can use it for searching in xml as well as adding new nodes with content in it. (And sorry i dont know how to load xml from client side and display it.)
but this fiddle demo will be helpful in adding content in xml and searching in it.
Hope it helps :)
If you want to achieve this on the client side you can parse your xml into a document object:
See
https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML
and
http://www.w3schools.com/xml/tryit.asp?filename=tryxml_parsertest2
And then manipulate it like you would the DOM of any html doc, e.g. createElement, appendChild etc.
See https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
Then to serialize it into a String again you could use https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
Persisting the data
Writing to a local file is not possible in a cross-browser way. In IE you could use ActiveX to read/write file.
You could use cookies to store data on the client side, if your data keeps small enough.
In HTML5 you could use local storage, see http://www.w3schools.com/html/html5_webstorage.asp
Try to use these two package one to convert to json and when is finish the other to come back
https://www.npmjs.com/package/xml2json
https://www.npmjs.com/package/js2xmlparser

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.

node_xslt documentation or examples not available

Hello,
I am new to xml, xsl, but I want to use node_xslt to Transform XML documents.
I have seen the nodejs page for this https://www.npmjs.com/package/node_xslt and https://developer.mozilla.org/en-US/docs/XSLT/PI_Parameters, but it does not contains any example, so can someone provide me some link or examples through which I can understand about this..
Thank you very much , I have got answer of my question,
The Link http://www.tutorialspoint.com/xslt/xslt_syntax.htm is very useful,
I have require to do just the following
var xslt = require('node_xslt');
var document = xslt.readXmlFile('path of xml file');
var stylesheet = xslt.readXsltFile('path of xslt file');
var transformedString = xslt.transform(stylesheet, document, []);
This will give us the HTML by using xml and xslt, can be check by print this..
console.log("transformedString>>>>" + transformedString);

Open XML content in another window, using JavaScript

I understand I cannot save XML content to a local file, because of security restrictions. but is there a way I can show the XML content in another browser window, as
Window.Open(xmlString, . .. );
that would work the same as -
Window.Open(URL, . . .);
I cannot use server-side language.
I can use javaScript \ jQuery. (I already use them to create the XML)
I can have a template XML file, near my HTML. Is there a way to display the template file and change its content ? almost the same as window.open: is it possible open a new window with modify its DOM or How to write JavaScript to a separate window? but I need to change XML nodes, and not HTML.
EDIT 1: try using myXmlWindow.document.write(xmlString)
=> I tried the suggested code -
var xmlString = xml2Str(xmlDocument);
myXmlWindow = window.open();
myXmlWindow.document.write(xmlString);
myXmlWindow.focus();
but it does not display the whole XML content, just the intern node values. and the new window still display "Connecting..." as it did not finish loading the content (missing close tag ???)
maybe I need to tell it is XML content and not HTML ???
my xmlString :
<root><device1>Name</device1><device2/><device3><Temprature_1>23.5</Temprature_1><Temprature_2>23.4</Temprature_2><Temprature_3>23.4</Temprature_3><Temprature_4>23.3</Temprature_4><Temprature_5>23.2</Temprature_5></device3></root>
the displayed content:
Name23.523.423.423.323.2
EDIT 2: my code -
function xml2Str(xmlNode) {
try {
// Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
return (new XMLSerializer()).serializeToString(xmlNode);
}
catch (e) {
try {
// Internet Explorer.
return xmlNode.xml;
}
catch (e) {
//Other browsers without XML Serializer
// alert('Xmlserializer not supported');
return('Xmlserializer not supported');
}
}
return false;
}
function fShow_xml_in_win() {
var xmlDocument = $.parseXML("<root/>");
var dev1 = xmlDocument.createElement('device1');
var dev2 = xmlDocument.createElement('device2');
var dev3 = xmlDocument.createElement('device3');
dev1.appendChild(xmlDocument.createTextNode('Name'));
xmlDocument.documentElement.appendChild(dev1);
xmlDocument.documentElement.appendChild(dev2);
xmlDocument.documentElement.appendChild(dev3);
var i;
var xNode;
for (i = 0; i < 5; i++) {
xNode = xmlDocument.createElement('Temprature_' + (i+1));
xNode.appendChild(xmlDocument.createTextNode( "myVal " + ((i+1) * 10) ));
dev3.appendChild(xNode);
}
var xmlString = xml2Str(xmlDocument);
alert(xmlString);
xmlString = "<?xml version='1.0' ?>" + xmlString; // I do not know how to add this node using parseXML :(
alert(xmlString);
myXmlWindow = window.open();
myXmlWindow.document.write(xmlString);
myXmlWindow.document.close(); // !! EDIT 3
myXmlWindow.focus();
return false;
}
EDIT 3: solved the "connecting..." problem
I just needed to add myXmlWindow.document.close();
You can open a blank window and then write content to it as follows:
myWindow=window.open('','','width=200,height=100')
myWindow.document.write(xmlString);
myWindow.focus()
You may need to do some work to format your xmlString, but I think this approach will do what you want. If your xmlString is formatted, try adding:
<?xml version="1.0" ?>
to the start of your string.
My understanding from your post, are
1.(From your firts point)
you get xml from somewhere which is not your control. My suggestion is why don't you get as JSON?
2.(From your second point)
If those XML is created by you means, Why aren't you try to write those XML from reference?
For example:
var reference = window.open();
reference.document.write(<some string goes here>)
3.(From your third point)
As per understanding from your second point. You can create xml. So why are you changing after write the document?
Note: Generally XML is used for Server-to-server communication, JSON is used for Server-to-client(browser) communication.

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