Loading local XML in IE - javascript

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.

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.

External JavaScript file is not defined

For a web project, I've included a JavaScript file as a script src, as shown here.
<script src="xml2json.js"> //same directory as the web project
Next, I tried to invoke a method within xml2json, called xml_str2json.
downloadUrl("ship_track_ajax.php", function(data) {
var xml_string = data.responseText; //an XML string
//A parser to transform XML string into a JSON object is required.
//Use convert XML to JSON with xml2json.js
var markers = xml2json.xml_str2json(xml_string);
}
However, console log indicates "Uncaught ReferenceError: xml2json is not defined", even though xml2json is included as a script src. Can anyone tell me as to what is wrong?
You have to call the function directly in javascript without reffering the filename as like
xml_str2json(xml_string);
If the function is defined in any of the included file it will be invoked.
I hope this will solve your problem
Maybe you should try this:
var json = xml2json(parseXml(xml), " ");
See Demo from https://github.com/henrikingo/xml2json

Loading and reading XML files in cocos2d-x 3.0 javascript scripts

How should one proceed to load XML content from a javascript script in cocos2d-x 3.0?
I need to parse an XML file but DOMParser is unavailable:
var text="<note>";
text=text+"<content>whatever blablabla</content>";
text=text+"</note>";
var parser=new DOMParser();
var doc=parser.parseFromString(text,'text/xml');
results in ReferenceError: DOMParser is not defined.
How should I proceed to load and manipulate the XML?
Even this solution fails:
var doc = document.implementation.createDocument("");
ReferenceError: document is not defined.
From the V2.2.1 documentation I tried the SAXParser to no avail:
cc.SAXParser.getInstance().parse(fullPath);
TypeError: cc.SAXParser is undefined
To paliate to the removal of cc.SAXParser in cocos2d-x 3.0 the solution is to use a pure javascript parser until a better solution is made available.

xslt with xpath that get some information from xml file doesn't work in JavaScript

I've got an xml file. It is meant for being transformed by xslt processor. The specific template is ready, however it use some information from two additional xml files. All information is used to produce the proper output.
It works fine when I open the main xml file with my browser. The problem is: the result is just a fragment of website, it is an HTML element ready for being appended as a child. That is why I want to transform the xml with the xslt processor within a JavaScript function. Unfortunatelly, the result is half-way done. All what don't need the additional information from these two xml files imported by xpath expression is transformed well. The rest is shortly speaking absent.
JavaScript:
var xhttp = new XMLHttpRequest()
var xsltProcessor = new XSLTProcessor()
xhttp.open("GET", "contentTemplate.xsl", false)
xhttp.send()
xsltProcessor.importStylesheet(xhttp.responseXML)
function buildElement(what) {
var xmlDoc = document.implementation.createDocument("", "root", null)
xmlDoc.documentElement.appendChild(xmlDoc.createElement(what))
var resultDocumentFragment = xsltProcessor.transformToFragment(xmlDoc, document)
return resultDocumentFragment
}
xslt:
there is lots of stuff, I paste just the xslt with xpath expression
<xsl:variable name="extInfo" select="document('tagAvailableToAdd.xml')/root"/>
<xsl:for-each select="$extInfo/tag">
<option>
<xsl:attribute name="value"><xsl:value-of select="tagName"/></xsl:attribute>
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
and that is just absent. Just like no information was delivered.
EDIT:
it works in firefox, doesn't in chrome. I need to improve it. Actually, I don't know how.
xslt:
there is lots of stuff, I paste just
the xslt with xpath expression
<xsl:variable name="extInfo" select="document('tagAvailableToAdd.xml')/root"/>
<xsl:for-each select="$extInfo/tag">
<option>
<xsl:attribute name="value"><xsl:value-of
select="tagName"/>
and that is just absent. Just like no
information was delivered.
Some possible reasons for this behaviour:
The URI of the XML file is not the right one. This is a relative URI and this specific URI will mace the XSLT processor look for a file named 'tagAvailableToAdd.xml' and residing at the base-uri of the stylesheet. However, in this case the stylesheet is obtained dynamically and this means it doesn't have any base-uri. This is the most possible reason for the problem.
The Javascript doesn't have permissions to access files in the local file system.
The document() function isn't allowed by default by the XSLT processor.
The text contained in the file is not a well-formed XML document.
The top element of the XML file is not named root.
Solution: Specify an absolute URI as the argument to the document() function.
I thought I had solved the problem, however an issue in firefox has occured.
Nevertheless, I concern chrome my native browser, that is why i'm glad I made it work in this program. That is the change I implemented in JavaScript:
function talkToServer(address, synch, func) {
func = typeof(func) != 'undefined' ? func : null
xhttp.open(method, address, synch)
xhttp.onreadystatechange = func
xhttp.send()
}
function getXPath(query) {
return document.evaluate(query, xhttp.responseXML, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null)
}
function buildElement(what) {
var xmlDoc = document.implementation.createDocument("", "root", null)
xmlDoc.documentElement.appendChild(xmlDoc.createElement(what))
switch(what) {
case "windowElement":
talkToServer("tagAvailableToAdd.xml", false)
var additionalInfo = getXPath("/root/tag")
var aim = xmlDoc.documentElement.getElementsByTagName("windowElement")[0]
for(i=0;i<additionalInfo.snapshotLength;i++)
aim.appendChild(additionalInfo.snapshotItem(i).cloneNode(true))
talkToServer("cssTemplates.xml", false)
additionalInfo = getXPath("/root/*")
aim.appendChild(xmlDoc.createElement("css"));
aim = aim.getElementsByTagName("css")[0]
for(i=0;i<additionalInfo.snapshotLength;i++)
aim.appendChild(additionalInfo.snapshotItem(i).cloneNode(true))
break;
}
var resultDocumentFragment = xsltProcessor.transformToFragment(xmlDoc, document)
return resultDocumentFragment
}
in xslt now I have all information in , so there is no need to import any external info.
main function is buildElement. I'm sure everybody can see what it does. It'a aim is to provide sth I can "paste" to HTML document.
In chrome it works. In firefox says: Node cannot be used in a document other than the one in which it was created" code: "4, and points at return statement in getXPath function. I don't know how ti fix it, but who cares, it is just firefox (I know it's stupid). In IE it suck, because xhttp is XHttpRequest object, but I believe, that when I provide ActiveX it should give what I want.
If you feel you can help me with the firefix issue, write a comment.

Categories

Resources