I'm trying to display some XML data in a jsp file.
I'm using EL to get the data below:
<xml id="xmlData">
<c:out value="${xmlform.myXmlData}" escapeXml="false"/>
</xml>
How can I get reference to this xml document using javascript?
var xmlDoc = document.getElementById("xmlData"); //reference to the xml element
var xmlData = xmlDoc.[how to reference xmlDoc to get data?]
var fields = xmlData.documentElement.selectNodes("field");
for (var i=-; i<fields.length;etc...
So the JSP-Server write the XML-tree directly in the HTML-code. I hope this could be helpful for you.
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(document.getElementById("xmlData").innerHTML ,"text/xml");
var fields = xmlDoc.documentElement.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
console.log(fields[i].firstChild.data); // fields[i].attributes, fields[i]childNodes, ...
}
or shorter:
var xmlData = document.getElementById("xmlData");
var fields = xmlData.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
console.log(fields[i].firstChild.data);
}
Here is how you can parse XML in javascript.
var xmlDoc;
function parsexml(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml"); //txt is your xml data
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
}
function getElementFromXML(tagname)
{
return xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
You have to load your xml file in and then find and manipulate the Nodes as needed.
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - which can then be manipulated with JavaScript.
W3Schools example
Related
I have 2 xml documents stored which I get from an AJAX post request and I would like to check if they are the same. Obviously xml1 == xml2 is not working. Is there another way that I could make this work?
Try this. It parses the XML document using the method in this question and compares the two using isEqualNode.
function parseXMLString(xmlString) {
var xmlDoc;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlString);
}
return xmlDoc;
}
var xmlObj1 = parseXMLString('<hello>world</hello>');
var xmlObj2 = parseXMLString('<hello>world</hello>');
var xmlObj3 = parseXMLString('<hello>world2</hello>');
var xmlObj4 = parseXMLString('<hello2>world</hello2>');
console.log(xmlObj1.isEqualNode(xmlObj2));
console.log(xmlObj1.isEqualNode(xmlObj3));
console.log(xmlObj1.isEqualNode(xmlObj4));
If you're using jQuery, you can parse the XML document using parseXML().
I'm having a lot of difficulty with this project.
My aim is to write the results of a HTML form to an XML Document using Javascript.I have absolutely no idea how to do it.
Reason why I'm coming here is that I want to be sure that I'm on the right track. So far, I'm writing only one line "\n" just to test things out.
Here is my current JavaScript
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function StoreRegXml()
{
xhr.open("GET", "php.php?" + Number(new Date), true);
xhr.onreadystatechange = getData;
xhr.send(null);
}
function getData()
{
if ((xhr.readyState == 4) && (xhr.status == 200))
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filename = "customer.xml";
var file = fso.CreateTextFile(filename, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.Close();
}
}
Am I on the right track?
Edit: I'm adding alerts('test1'); to see where the code is going wrong and it stops at
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
Any ideas?
Inside the browser to create and populate an XML DOM document you can use the W3C DOM APIs with e.g.
var xmlDoc = document.implementation.createDocument(null, 'root', null);
var foo = xmlDoc.createElement('foo');
foo.textContent = 'bar';
xmlDoc.documentElement.appendChild(foo);
console.log(xmlDoc);
This creates an in memory XML DOM document, not an XML file. You can then for instance send the xmlDoc with XMLHttpRequest to the server.
This is my working piece of code for IE<10, FF and Safari.
var xmlDoc;
function importXML(xmlfile)
{
var element;
var xmlloaded = false;
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception)
{
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
IE10 give me error in the following line of code: doesn't support load
xmlDoc.load(xmlfile);
element = xmlDoc.documentElement;
xmlloaded = true;
}
else
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = element = xmlDoc.documentElement;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded)
{
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
element = xmlDoc.documentElement;
xmlloaded = true;
}
}
I need this to work with IE 10 too.
I know the solution is here http://blogs.msdn.com/b/ie/archive/2012/07/19/xmlhttprequest-responsexml-in-ie10-release-preview.aspx because in another question on stackvoerflow a user said he found a solution there but he didn't wrote the mod.
I didn't write myself the above code and I'm a beginner so I don't know how to operate.
Javascript can't access the local file system for security reasons. If you have access to the required file and a server of some type, put the file on the server and access it from there using a URL.
I have the following, which loads XML from a web site and parses it:
function load() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = parse;
xhttp.open('GET', 'http://...XML.xml', false);
xhttp.send();
}
function parse() {
xmlDoc = xhttp.responseXML.documentElement.childNodes;
for (var i = 0; i < xmlDoc.length; i++) {
nodeName = xmlDoc[i].nodeName;
...
}
After I loading this, I store it in localStorage and I can retrieve it as a string. I need to be able to convert it back to a xml document just like:
xmlDoc = xhttp.responseXML.documentElement.childNodes;
does, so i can parse it. I have been looking for awhile now and can not figure it out.
Thanks in advance.
Based on the answer here XML parsing of a variable string in JavaScript Credit to #tim-down
You need to create an XML parser. Then pass the string into your parse instance. Then you should be able to query it as per before.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("[Your XML string here]");
I'm using the following parser to parse xml
function parseXML(text) {
var doc;
if(window.DOMParser) {
var parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
else {
throw new Error("Cannot parse XML");
}
return doc;
}
I can't understand why it isn't working on my XML document, obtained via AJAX.
Result via AJAX request:
X-Powered-By PHP/5.2.11
Content-Length 887
Keep-Alive timeout=5, max=95
Connection Keep-Alive
Content-Type text/xml
<?xml version="1.0" encoding="UTF-8"?>
<xml_test>wont work!</xml_test>
Test Code:
var xml = parseXML(data);
$(xml).find("xml_test").each(function()
{
console.info('found xml_test... never happen..');
});
But if I use it like this it works nicely!
var data = '<xml_test>works</xml_test>';
var xml = parseXML(data);
$(xml).find("xml_test").each(function()
{
alert('this works!');
});
I know that this is a specific question but I would appreciate your help and/or suggestions...
Thanks in advance
Pedro
If you use jQuery to request your resource, you should already get XML DOM document in case it was served with text/xml mime-type. Thus no need to parse.
If you're getting your XML via Ajax, there's no need to parse it because the browser will do it for you. Simply use the responseXML property of the XMLHttpRequest object, which will give you an XML document object. jQuery wraps this using "xml" for the dataType:
$.ajax({
type: "GET",
url: "foo.xml",
dataType: "xml",
success: function(xml) {
alert(xml.documentElement.nodeName);
}
});
I use this function and gives me good result:
var myLoadXml = function(s){
var objxml = null;
if(document.implementation && document.implementation.createDocument) {
var objDOMParser = new DOMParser();
objxml = objDOMParser.parseFromString(s, "text/xml");
} else if (window.ActiveXObject) {
objxml = new ActiveXObject('MSXML2.DOMDocument.3.0');
objxml.async = false;
objxml.loadXML(s);
}
return objxml;
};
var xml = myLoadXml(data);
$(xml).find("xml_test").each(function()
{
console.info('found xml_test... never happen..');
});
EDIT
Example
** EDIT II **
function parseXML(text) {
var doc;
if (typeof text == 'object'){ // check type of text
return text;
}
if(window.DOMParser) {
var parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
else {
throw new Error("Cannot parse XML");
}
return doc;
}
If you are using jQuery (as your test code suggests), you can simply pass the xml to it.
var xml = $(data);