I have a textarea where I paste an XML file and convert it to JSON with simple JavaScript.
I want to modify the XHTML on the client with XSLT and produce a new XML that will be converted to JSON.
I get CORS errors all the time.
My code is:
<textarea id="xmltext" name="xmltext"></textarea>
<button onclick="xml2xslt()">transform</button>
function xml2xslt(){
var xslStylesheet;
var xsltProcessor = new XSLTProcessor();
var myDOM;
var xmlDoc;
var xhr = new XMLHttpRequest();
xhr.open("GET", "<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"><html><body><h2>My CD Collection</h2><table border="1"><tr bgcolor="#9acd32"><th>Title</th><th>Artist</th></tr><xsl:for-each select="catalog/cd"><tr><td><xsl:value-of select="title"/></td><td><xsl:value-of select="artist"/></td></tr></xsl:for-each></table></body></html></xsl:template></xsl:stylesheet>", false);
xhr.overrideMimeType("text/xml")
xhr.send(null);
xslStylesheet = xhr.responseXML;
xsltProcessor.importStylesheet(xslStylesheet);
// load the xml file
xhr = new XMLHttpRequest();
xhr.open("GET", "<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><country>USA</country><company>Columbia</company><price>10.90</price><year>1985</year></cd></catalog>", false);
xhr.overrideMimeType("text/xml")
xhr.send(null);
xmlDoc = xhr.responseXML;
var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
document.getElementById("xmltext").textContent = "";
myDOM = fragment;
document.getElementById("xmltext").appendChild(fragment);
}
what path should I place in url of xhr.open("GET",url,false); to get the xml code? xsl code can be hard coded because I just remove a prefix of the tags.
How can I export the new xml so as to JSON.parse() it?
If you have the XML and/or XSLT data as a string then use DOMParser to parse them e.g.
xslStylesheet = new DOMParser().parseFromString(yourXSLTString, 'application/xml');
then pass that xslStylesheet document to the importStylesheet method of the XSLTProcessor. There is no need for using XMLHttpRequest.
Do the same for the XML document e.g.
xmlDoc = new DOMParser().parseFromString(`<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><country>USA</country><company>Columbia</company><price>10.90</price><year>1985</year></cd></catalog>`, 'application/xml');
Related
I am parsing my XML file in HTML and it parses well when I run it in Chrome/Edge browsers, but when I run it in Firefox, it throws this error:
XML Parsing Error: not well-formed
Location: http://127.0.0.1:5500/List.xml
Line Number 21, Column 2:
This is my HTML where I parse it:
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == XMLHttpRequest.DONE) {
var xmlData = xml.responseXML;
if (!xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var PDF = xmlData.getElementsByTagName("PDF");
var web = PDF[0].getElementsByTagName("link")[0].firstChild.data;
}
}
}
xml.open('GET', 'List.xml', true);
xml.send(null);
</script>
<?xml version = "1.0" ?>
<List>
<PDF>
<id>1</id>
<link>https://www.mywebpage.com/AA.pdf</link>
</PDF>
</List>
</xml>
Your XML is not well-formed. Remove the last </xml> tag.
The <?xml version = "1.0" ?> construct is not a opening element tag that has to be closed. It is an XML declaration.
I'm trying to dispay the one node e.g. "title" on a internal html page but I need it to pull the data from an XML document that is saved on my Desktop but it doesn't seem to be finding the XML document. I'm not to sure what to add or how to combat this problem? Any help would be much appreciated! Many thanks
var parser, xmlDoc;
var text = loadXMLDoc("/Desktop/test.xml");
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
First of all you can't access any files from the absolute path of your system due to security reasons. you must need to upload file at first place, there after you can process the XML content.
follow link below tried to create small snippet for you.
HTML:
<div>
<label id="txtFileInfo"></label>
<input id="xmlFile" type="file">
</div>
JS:
(function($){
$('#xmlFile').unbind('change')
.bind('change', function(e){
if(this.files.length > 0){
var file = this.files[0];
if(file.type == 'text/xml'){
setTimeout(function(){
console.log('Reader');
var reader = new FileReader();
reader.addEventListener('load', function(){
console.log(reader.result);
parser = new DOMParser();
xmlDoc = parser.parseFromString(reader.result, file.type);
console.log(xmlDoc);
});
reader.readAsDataURL(file);
}, 100);
}
// $('#txtFileInfo').text('Type: '+ file.type);
}
});
})($);
https://codepen.io/smtgohil/pen/gGWoRe
All the best.
I am sending an xml response from my servlet to my html page. I receive it via the xmlresponse object of the xmlhttprequest object. My xml document contains a xsl:stylesheet as an element I want to extract this element and execute that xslt code in my java script.
Is it possible?
This is my xml code :
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
Version="2.0" IssueInstant="2012-05-22T13:40:52:390" ProtocolBinding="urn:oasis:na
mes:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="localhos
t:8080/consumer.jsp">
<UserID>
xyz
</UserID>
<testing>
text
</testing>
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
http://localhost:8080/saml/SProvider.jsp
</saml:Issuer>
<xslt>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" />
<xsl:template match="/">
UserID : <xsl:copy-of select="//UserID"/>
testing : <xsl:copy-of select="//testing"/>
</xsl:template>
</xsl:stylesheet>
</xslt>
</samlp:AuthnRequest>
Once I get this xml string from the ajax response, I want to convert it into xml, extract the xslt part and execute it and show the output in a text area.
EDIT2
What is wrong with this code :
var xmlDoc=xmlhttp.responseXML;
//var xmltext=new XMLSerializer().serializeToString(xmlDoc);
var xsltProcessor = new XSLTProcessor();
var element=xmlDoc.getElementsByTagNameNS("http://www.w3.org/1999/XSL/Transform","stylesheet");//
//document.forms['my']['signature'].value=xmltext;
var stylesheet=xsltProcessor.importStylesheet(element[0]);
var result=xsltProcessor.transformToDocument(xmlDoc);
var xmltext1=new XMLSerializer().serializeToString(result);
document.forms['my']['signature2'].value = xmltext1;
The output(xmltext1) for the xslt transformation is -
<transformiix:result xmlns:transformiix="http://www.mozilla.org/TransforMiix">
UserID : 1212
Testing : 1212
</transformiix:result>
But if you see in the xslt code, the outputmethod is set to "text". then why are xml tags included in the output?
Answer
This gives the exlpanation for edit2. Thanks for the answers:)
This is what worked for me, though I only tested it in the newest chrome:
var getNsResolver = function (element) {
var ns = {
samlp: 'urn:oasis:names:tc:SAML:2.0:protocol',
xsl: 'http://www.w3.org/1999/XSL/Transform'
};
return function (prefix) {
return ns[prefix] || null;
};
};
var handleResponse = function (xhr) {
var
doc = xhr.responseXML,
xsl = doc.evaluate('/samlp:AuthnRequest/xslt/xsl:stylesheet', doc, getNsResolver(doc.documentElement), XPathResult.ANY_TYPE, null).iterateNext(),
processor = new XSLTProcessor(),
result;
processor.importStylesheet(xsl);
result = processor.transformToFragment(doc, document);
document.getElementById('foo').value = result.textContent;
};
window.addEventListener('load', function () {
var request = new XMLHttpRequest();
request.addEventListener('load', function (evt) {
handleResponse(request);
}, false);
request.open('GET', 'sample.xml', true); // sample.xml contains the xml from the question
request.send();
}, false);
This is what I use to get namespaced xml from an xmlHttpRequest (in your case ns=xsl, not tested):
var xml=xhr.responseXML;
var elts = (xml.getElementsByTagNameNS)?xml.getElementsByTagNameNS("ns","tag"):xml.getElementsByTagName("ns\:tag");
Note that you can only use responseXML if the server returns well formed xml. If not, you'll need to parse xhr.responseText.
I'm using this ATM, works great!
Its a parser written on jQuery
http://www.jongma.org/webtools/jquery/xslt/
I have a xml file whose content is
<?xml version="1.0" encoding="UTF-8"?>
<ReturnMessage>
<root>ReturnMessage</root>
<cancelMessage>Request cancelled. /cancelMessage>
<confirmMessage>Click 'Create Document' to continue.</confirmMessage>
</ReturnMessage>
I load my xml like this
var result = responseText;
if (document.implementation && document.implementation.createDocument)
{
alert("firefox");
xml=document.implementation.createDocument("","",null);
xml.load(result);
}
When execute the below code
var cnfmMsgCnt = xml.getElementsByTagName("confirmMessage");
alert(cnfmMsgCnt.lenght);
it alerts a 0 is firefox.
var displayMsg = xml.getElementsByTagName("confirmMessage").item(0).text
also does not provide any output in FF.
It works perfect in IE but it is not working in Firefox.
The method load() takes a file name as argument, not an XML string. See https://developer.mozilla.org/en/DOM/document.load (and more normative: W3C DOM Level 3 Load & Save module)
What you probably want is explained here https://developer.mozilla.org/en/Parsing_and_serializing_XML
var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");
I have a peice of code that i call inside of $("document).ready() in jquery that tries to open an xml file and parse it.
$.get('cal.xml', function(data){
alert(data);
var xmlDoc = $.parseXML(data);
var $xml = $(xmlDoc);
});
the alert that pops up is "[object Document]" rather than the actual text of the xml which then throws a problem with $.parseXML(data) saying that
"Uncaught Invalid XML: undefined" (implying that data is undefined).
here is the XML file
<?xml version="1.0"?>
<cal>
<today>
<event>
<time>
6:30pm EST
</time>
<title>
nothing
</title>
</event>
</today>
</cal>
Could someone help me simply read in this XML file and set it up for parsing?
Try to set the dataType option to xml:
$.get('cal.xml', function(data){
alert(data);
}, 'xml');
"data" should be at this point parsed xml.
here is the fiddle hope it'll help http://jsfiddle.net/ah2Y8/1/
OR
http://jsfiddle.net/ah2Y8/2/
code to convert string to XML object
function str2XML (str) {
var xml;
if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
} else {
var parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
return xml;
}