I am trying to do an XSL transformation.
However, whenever the variable with a document fragment is referenced, the transformation seems to fail.
I created a JSFiddle to demonstrate the issue. The XML in the example is a dummy document to allow the XSLT to run.
What am I doing wrong?
Javascript:
var xml = [
'<p xmlns="http://www.w3.org/1999/xhtml">',
'<\/p>'
].join('\n');
var xsl = [
'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">',
'<xsl:variable name="xmlVar">',
'<aaaa value="It works"\/>',
'<\/xsl:variable>',
'<xsl:template match="\/">',
'<ROOT>',
//works ok after commenting out
'<xsl:value-of select="$xmlVar\/aaaa\/#value"\/>',
'<\/ROOT>',
'<\/xsl:template>',
'<\/xsl:stylesheet>'
].join('\n');
var domParser = new DOMParser();
var xmlDoc = domParser.parseFromString(xml, 'application/xml');
var xslDoc = domParser.parseFromString(xsl, 'application/xml');
var xsltProc = new XSLTProcessor();
xsltProc.importStylesheet(xslDoc);
try{
var result = xsltProc.transformToFragment(xmlDoc, document);
} catch(exc) {
document.getElementById('error').innerHTML = exc;
}
function encodeStr(rawStr) { return rawStr.replace(/[\u00A0-\u9999<>\&]/gim,
function(i){
return '&#'+i.charCodeAt(0)+';'
});
}
document.getElementById('xslText').innerHTML = encodeStr(xsl);
document.getElementById('result').innerHTML = encodeStr((new XMLSerializer).serializeToString(result));
HTML:
<pre id='xslText'>
</pre>
<pre id='result'>
</pre>
<pre id='error'>
</pre>
In XSLT 1.0 you need to use an extension function like exsl:node-set (http://exslt.org/exsl/functions/node-set/index.html) to convert a variable value of type result tree fragment (https://www.w3.org/TR/xslt-10/#section-Result-Tree-Fragments) to a node-set to be able to use XPath on the nodes e.g.
var xml = [
'<p xmlns="http://www.w3.org/1999/xhtml">',
'<\/p>'
].join('\n');
var xsl = [
'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:exsl="http://exslt.org/common" xmlns:msxml="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="exsl msxml">',
'<xsl:variable name="xmlVar">',
'<aaaa value="It works"/>',
'<\/xsl:variable>',
'<xsl:template match="/">',
'<div>',
'<xsl:choose><xsl:when test="function-available(\'exsl:node-set\')"><xsl:value-of select="exsl:node-set($xmlVar)/aaaa/#value"/><\/xsl:when><xsl:when test="function-available(\'msxml:node-set\')"><xsl:value-of select="msxml:node-set($xmlVar)/aaaa/#value"/><\/xsl:when><\/xsl:choose>',
'<\/div>',
'<\/xsl:template>',
'<\/xsl:stylesheet>'
].join('\n');
var domParser = new DOMParser();
var xmlDoc = domParser.parseFromString(xml, 'application/xml');
var xslDoc = domParser.parseFromString(xsl, 'application/xml');
var xsltProc = new XSLTProcessor();
xsltProc.importStylesheet(xslDoc);
try{
var result = xsltProc.transformToFragment(xmlDoc, document);
document.getElementById('result').appendChild(result);
} catch(exc) {
document.getElementById('error').innerHTML = exc;
}
<pre id='xslText'>
</pre>
<pre id='result'>
</pre>
<pre id='error'>
</pre>
Drawback in terms of cross-browser compatibility with client-side XSLT 1 is that Microsoft use MSXML 3 or 6 in IE and Edge to provide XSLT support and unfortunately MSXML has its own proprietary namespace for such an extension function instead of supporting EXSLT.
Fiddle updated to http://jsfiddle.net/29pwf84c/14/.
Related
I have the following XML, it's coming as string from a request. How can I get the capital value (Washington, DC Paris)?
<Country>
<USA>
<Capital>"Washington, D.C"</Capital>
</USA>
<France>
<Capital>"Paris"</Capital>
</France>
</Country>
Use a DomParser :
var xml = `<Country>
<USA>
<Capital>"Washington, D.C"</Capital>
</USA>
<France>
<Capital>"Paris"</Capital>
</France>
</Country>`
var parser = new DOMParser();
var doc = parser.parseFromString(xml, "application/xml");
doc.querySelectorAll('Capital').forEach(
(cap) => console.log(cap.textContent));
Adding the answer with jquery. With jquery it can be easily done as,
var text = `<Country>
<USA>
<Capital>"Washington, D.C"</Capital>
</USA>
<France>
<Capital>"Paris"</Capital>
</France>
</Country>`;
$(text).find("Capital").each(function(){
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<root xmlns='http://www.w3.org/2005/Atom' xmlns:element='http://search.yahoo.com/mrss/'>
<element:group>
<element:content url='https://myrequiredurl.com' otherattr='360' otherattr='640' otherattr='somthng' medium='smtng'/>
<element:content url='https://myrequiredurl.com' otherattr='720' otherattr='1280' otherattr='smtng' medium='smtng'/>
<element:content url='https://myrequiredurl.com' otherattr='1080' otherattr='1920' otherattr='smtng' medium='smtng'/>
</element:group>
</root>
Above is my xml doc i need to get the 'url' attribute from first '<element:content/>' tag i tried the ways mentioned in w3schools.com but i had
no luck some help is much appreciated i need to access it using javascript sorry for bad question framing
You can simply achieve this using dom manupulation.
HTML:
<p id="show"></p>
Javascript:
var urlList = [];
var txt = "<root xmlns='http://www.w3.org/2005/Atom' xmlns:element='http://search.yahoo.com/mrss/'>" +
"<element:group>" +
"<element:content url='https://1myrequiredurl.com' otherattr='somthng' medium='smtng'> </element:content>" +
"<element:content url='https://2myrequiredurl.com' otherattr='smtng' medium='smtng'> </element:content>" +
"<element:content url='https://3myrequiredurl.com' otherattr='smtng' medium='smtng'> </element:content>" +
"</element:group>" +
"</root>";
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // For Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var group = xmlDoc.getElementsByTagName("root")[0].childNodes[0].childNodes;
for (var content in group) {
if (!isNaN(content)) {
var url = group[content].getAttribute("url")
urlList.push(url);
}
}
document.getElementById("show").innerHTML = urlList.join("</br>");
P.S: "You cannot add multiple attributes with the same name".
you can find the solution here: https://jsfiddle.net/vineetsagar7/3od130pd/2/
This is the xml string stored in a variable "xml".
<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:extratask="http://extratask" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn">
<bpmn:process id="Process_1" isExecutable="false">
<bpmn:task id="Task_15xgmrn" name="Select1Select5" extratask:entity="Select1" extratask:action="Select5" />
<bpmn:task id="Task_0ditp3t" name="Select2Select6" extratask:entity="Select2" extratask:action="Select6" />
<bpmn:task id="Task_0p68hrl" name="Select3Select6" extratask:entity="Select3" extratask:action="Select6" />
</bpmn:process>
</bpmn:definitions>
So far, I have just tried to read the nodes "bpmn:task" into console with this code but getting blank array.
if(window.DOMParser){
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
}else{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xml);
}
console.log(xmlDoc.getElementsByTagName("bpmn:task"));
please someone make me understand that where I am going wrong, and another thing is that I want to insert some attributes into "bpmn:task" tags.
The attribute xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" denotes a custom namespace for your XML, which means you have to use getElementsByTagNameNS() with the give namespace to get the tags
xmlDoc.getElementsByTagNameNS("http://www.omg.org/spec/BPMN/20100524/MODEL","task")
var xml = '<?xml version="1.0" encoding="UTF-8"?><bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:extratask="http://extratask" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn"><bpmn:process id="Process_1" isExecutable="false"><bpmn:task id="Task_15xgmrn" name="Select1Select5" extratask:entity="Select1" extratask:action="Select5" /><bpmn:task id="Task_0ditp3t" name="Select2Select6" extratask:entity="Select2" extratask:action="Select6" /><bpmn:task id="Task_0p68hrl" name="Select3Select6" extratask:entity="Select3" extratask:action="Select6" /></bpmn:process></bpmn:definitions>';
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
console.log(xmlDoc.getElementsByTagNameNS("http://www.omg.org/spec/BPMN/20100524/MODEL","task"));
I want to convert an xml element like this:
<asin>B0013FRNKG</asin>
to string in javascript
I used XMLSerializer:
new XMLSerializer().serializeToString(xml);
the string only shows on alert() and in the console. On the page it just says
[object Element][object Element]
I want to get the string.
You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:
document.getElementById('SomeDiv').appendChild(xml);
and if you just want the full xml string to be displayed:
var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);
<script type='text/javascript'>
function xmlToString(xmlData) {
var xmlString;
//IE
if (window.ActiveXObject){
xmlString = xmlData.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else{
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
}
</script>
use this in case of IE for browser compatibility issues.
function getXmlString(xml) {
if (window.ActiveXObject) { return xml.xml; }
return new XMLSerializer().serializeToString(xml);
}
alert(getXmlString(xml));
Did you try enclosing the result like in…
(new XMLSerializer()).serializeToString(xml)
Also, I'd use console instead to see the content better:
console.log((new XMLSerializer()).serializeToString(xml));
If the DOM element <asin>B0013FRNKG</asin> is stored in the object element, then you can access the value using:
element.textContent
follow this to print,append data from xml data stored as string inside javscript
txt="<papers>"+"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<paper>"+
"<author>athor name</author>"+
"<title>title</title>"+
"<path>path</path>"+
"<track>which tack</track>"+
"</paper>"+
"<papers>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
x=xmlDoc.getElementsByTagName("paper");
for (var i = 0; i < x.length; i++) {
var athor =x[i].childNodes[0].firstChild.nodeValue;
var title = x[i].childNodes[1].firstChild.nodeValue;
var path = x[i].childNodes[2].firstChild.nodeValue;
var tack =x[i].childNodes[3].firstChild.nodeValue;
//do something with these values...
//each iteration gives one paper details
var xml=document.getElementById("element_id");//<div id="element_id"></div>
var li = document.createElement("br");// create a new <br>
newlink = document.createElement('A'); // creating an <a> element
newlink.innerHTML = athor;// adding <a>athor value here</a>
newlink.setAttribute('href', path);//
newlink.appendChild(li);// athor<br>
document.getElementById("element_id").appendChild(newlink);//finaly it becomes <div id="element_id">athor<br></div>
}
Is it possible to create an XML file with some data in JavaScript? I have the data stored in variables.
I've googled around a bit and it doesn't seem like it's talked about much. I thought I could use XMLWriter such as this:
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
as stated in this tutorial: EHow Tutorial
However, when I execute this code, I get the following error:
ReferenceError: XMLWriter is not defined
How can I solve this error?
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
JavaScript handles XML with 'XML DOM objects'.
You can obtain such an object in three ways:
1. Creating a new XML DOM object
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3. Parsing a string containing serialized XML
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
Note:
It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
Consider that we need to create the following XML document:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
Example
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
xml-writer(npm package)
I think this is the good way to create and write xml file easy.
Also it can be used on server side with nodejs.
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());
Simply use
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
this work for me..
var xml = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");
developer.mozilla.org/en-US/docs/Web/API/DOMParser
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
Your code is referencing this library
You can include it, and then your code in question should run as is. If you want to do this without prepending the library & build it with builtin functions only - follow answer from #Seb3736.
In Browser Example
<html>
<head>
<script src="Global.js" language="javascript"></script>
<script src="XMLWriter.js" language="javascript"></script>
<script language="javascript" type="text/javascript">
function genXML(){
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
//Do something... eg.
console.log(XML.ToString); //Yes ToString() not toString()
}
</script>
</head>
<body>
<input type="submit" value="genXML" onclick="genXML();">
</body>
</html>