How can I get the document object out of this?
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
In your example, xmlobject is the document object, according to MDC. According to w3schools, on IE, you need to use an IE-specific ActiveX object instead of DOMParser:
var xmlDoc, parser;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else { // Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
You've said that getElementById isn't working. Note that id is not a special attribute (an attribute of type "ID") in XML by default, so even if you're giving elements an id attribute, getElementById won't work (it should return null). Details in the W3C docs for getElementById. I've never done it, but I assume you'd assign an attribute the "ID" type via a DTD.
Without one, though, you can use other traversal mechanisms. For example (live copy):
var xmlDoc, parser, text, things, index, thing;
text =
'<test>' +
'<thing>Thing 1</thing>' +
'<thing>Thing 2</thing>' +
'</test>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else { // Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
things = xmlDoc.documentElement.getElementsByTagName('thing');
for (index = 0; index < things.length; ++index) {
thing = things.item(index);
display(index + ": " + getText(thing));
}
...where getText is:
function getText(element) {
return textCollector(element, []).join("");
}
function textCollector(element, collector) {
for (node = element.firstChild; node; node = node.nextSibling) {
switch (node.nodeType) {
case 3: // text
case 4: // cdata
collector.push(node.nodeValue);
break;
case 8: // comment
break;
case 1: // element
if (node.tagName == 'SCRIPT') {
break;
}
// FALL THROUGH TO DEFAULT
default:
// Descend
textCollector(node, collector);
break;
}
}
return collector;
}
(getText is a good example of why I use libraries like jQuery, Closure, Prototype, YUI, or any of several others for this stuff. You'd think it would be simple to get the text inside an element, and it is if the element has exactly one text node inside it [as our things do above]. If it doesn't, well, it gets complicated fast.)
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().
walk(document.body);
function walk (node)
{
var child, next;
switch (node.nodeType)
{
case 1: //Element
case 9: //Document
case 11: //Document fragment
child = node.firstChild;
while(child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // text node
textAndGet(node);
break;
}
}
function textAndGet(textNode)
{
var v = textNode.nodeValue;
var apiBuilder = "https://unshorten.me/s/";
var response
var link = v.search(/(?:https?:\/\/)?(?:(?:0rz\.tw)|(?:1link\.in)|(?:1url\.com)|(?:2\.gp)|(?:2big\.at)|(?:2tu\.us)|(?:3\.ly)|(?:307\.to)|(?:4ms\.me)|(?:4sq\.com)|(?:4url\.cc)|(?:6url\.com)|(?:7\.ly)|(?:a\.gg)|(?:a\.nf)|(?:aa\.cx)|(?:abcurl\.net)|(?:ad\.vu)|(?:adf\.ly)|(?:adjix\.com)|(?:afx\.cc)|(?:all\.fuseurl.com)|(?:alturl\.com)|(?:amzn\.to)|(?:ar\.gy)|(?:arst\.ch)|(?:atu\.ca)|(?:azc\.cc)|(?:b23\.ru)|(?:b2l\.me)|(?:bacn\.me)|(?:bcool\.bz)|(?:binged\.it)|(?:bit\.ly)|(?:bizj\.us)|(?:bloat\.me)|(?:bravo\.ly)|(?:bsa\.ly)|(?:budurl\.com)|(?:canurl\.com)|(?:chilp\.it)|(?:chzb\.gr)|(?:cl\.lk)|(?:cl\.ly)|(?:clck\.ru)|(?:cli\.gs)|(?:cliccami\.info)|(?:clickthru\.ca)|(?:clop\.in)|(?:conta\.cc)|(?:cort\.as)|(?:cot\.ag)|(?:crks\.me)|(?:ctvr\.us)|(?:cutt\.us)|(?:dai\.ly)|(?:decenturl\.com)|(?:dfl8\.me)|(?:digbig\.com)|(?:digg\.com)|(?:disq\.us)|(?:dld\.bz)|(?:dlvr\.it)|(?:do\.my)|(?:doiop\.com)|(?:dopen\.us)|(?:easyuri\.com)|(?:easyurl\.net)|(?:eepurl\.com)|(?:eweri\.com)|(?:fa\.by)|(?:fav\.me)|(?:fb\.me)|(?:fbshare\.me)|(?:ff\.im)|(?:fff\.to)|(?:fire\.to)|(?:firsturl\.de)|(?:firsturl\.net)|(?:flic\.kr)|(?:flq\.us)|(?:fly2\.ws)|(?:fon\.gs)|(?:freak\.to)|(?:fuseurl\.com)|(?:fuzzy\.to)|(?:fwd4\.me)|(?:fwib\.net)|(?:g\.ro.lt)|(?:gizmo\.do)|(?:gl\.am)|(?:go\.9nl.com)|(?:go\.ign.com)|(?:go\.usa.gov)|(?:goo\.gl)|(?:goshrink\.com)|(?:gurl\.es)|(?:hex\.io)|(?:hiderefer\.com)|(?:hmm\.ph)|(?:href\.in)|(?:hsblinks\.com)|(?:htxt\.it)|(?:huff\.to)|(?:hulu\.com)|(?:hurl\.me)|(?:hurl\.ws)|(?:icanhaz\.com)|(?:idek\.net)|(?:ilix\.in)|(?:is\.gd)|(?:its\.my)|(?:ix\.lt)|(?:j\.mp)|(?:jijr\.com)|(?:kl\.am)|(?:klck\.me)|(?:korta\.nu)|(?:krunchd\.com)|(?:l9k\.net)|(?:lat\.ms)|(?:liip\.to)|(?:liltext\.com)|(?:linkbee\.com)|(?:linkbun\.ch)|(?:liurl\.cn)|(?:ln-s\.net)|(?:ln-s\.ru)|(?:lnk\.gd)|(?:lnk\.ms)|(?:lnkd\.in)|(?:lnkurl\.com)|(?:lru\.jp)|(?:lt\.tl)|(?:lurl\.no)|(?:macte\.ch)|(?:mash\.to)|(?:merky\.de)|(?:migre\.me)|(?:miniurl\.com)|(?:minurl\.fr)|(?:mke\.me)|(?:moby\.to)|(?:moourl\.com)|(?:mrte\.ch)|(?:myloc\.me)|(?:myurl\.in)|(?:n\.pr)|(?:nbc\.co)|(?:nblo\.gs)|(?:nn\.nf)|(?:not\.my)|(?:notlong\.com)|(?:nsfw\.in)|(?:nutshellurl\.com)|(?:nxy\.in)|(?:nyti\.ms)|(?:o-x\.fr)|(?:oc1\.us)|(?:om\.ly)|(?:omf\.gd)|(?:omoikane\.net)|(?:on\.cnn.com)|(?:on\.mktw.net)|(?:onforb\.es)|(?:orz\.se)|(?:ow\.ly)|(?:ping\.fm)|(?:pli\.gs)|(?:pnt\.me)|(?:politi\.co)|(?:post\.ly)|(?:pp\.gg)|(?:profile\.to)|(?:ptiturl\.com)|(?:pub\.vitrue.com)|(?:qlnk\.net)|(?:qte\.me)|(?:qu\.tc)|(?:qy\.fi)|(?:r\.im)|(?:rb6\.me)|(?:read\.bi)|(?:readthis\.ca)|(?:reallytinyurl\.com)|(?:redir\.ec)|(?:redirects\.ca)|(?:redirx\.com)|(?:retwt\.me)|(?:ri\.ms)|(?:rickroll\.it)|(?:riz\.gd)|(?:rt\.nu)|(?:ru\.ly)|(?:rubyurl\.com)|(?:rurl\.org)|(?:rww\.tw)|(?:s4c\.in)|(?:s7y\.us)|(?:safe\.mn)|(?:sameurl\.com)|(?:sdut\.us)|(?:shar\.es)|(?:shink\.de)|(?:shorl\.com)|(?:short\.ie)|(?:short\.to)|(?:shortlinks\.co.uk)|(?:shorturl\.com)|(?:shout\.to)|(?:show\.my)|(?:shrinkify\.com)|(?:shrinkr\.com)|(?:shrt\.fr)|(?:shrt\.st)|(?:shrten\.com)|(?:shrunkin\.com)|(?:simurl\.com)|(?:slate\.me)|(?:smallr\.com)|(?:smsh\.me)|(?:smurl\.name)|(?:sn\.im)|(?:snipr\.com)|(?:snipurl\.com)|(?:snurl\.com)|(?:sp2\.ro)|(?:spedr\.com)|(?:srnk\.net)|(?:srs\.li)|(?:starturl\.com)|(?:su\.pr)|(?:surl\.co.uk)|(?:surl\.hu)|(?:t\.cn)|(?:t\.co)|(?:t\.lh.com)|(?:ta\.gd)|(?:tbd\.ly)|(?:tcrn\.ch)|(?:tgr\.me)|(?:tgr\.ph)|(?:tighturl\.com)|(?:tiniuri\.com)|(?:tiny\.cc)|(?:tiny\.ly)|(?:tiny\.pl)|(?:tinylink\.in)|(?:tinyuri\.ca)|(?:tinyurl\.com)|(?:tl\.gd)|(?:tmi\.me)|(?:tnij\.org)|(?:tnw\.to)|(?:tny\.com)|(?:to\.ly)|(?:togoto\.us)|(?:totc\.us)|(?:toysr\.us)|(?:tpm\.ly)|(?:tr\.im)|(?:tra\.kz)|(?:trunc\.it)|(?:twhub\.com)|(?:twirl\.at)|(?:twitclicks\.com)|(?:twitterurl\.net)|(?:twitterurl\.org)|(?:twiturl\.de)|(?:twurl\.cc)|(?:twurl\.nl)|(?:u\.mavrev.com)|(?:u\.nu)|(?:u76\.org)|(?:ub0\.cc)|(?:ulu\.lu)|(?:updating\.me)|(?:ur1\.ca)|(?:url\.az)|(?:url\.co.uk)|(?:url\.ie)|(?:url360\.me)|(?:url4\.eu)|(?:urlborg\.com)|(?:urlbrief\.com)|(?:urlcover\.com)|(?:urlcut\.com)|(?:urlenco\.de)|(?:urli\.nl)|(?:urls\.im)|(?:urlshorteningservicefortwitter\.com)|(?:urlx\.ie)|(?:urlzen\.com)|(?:usat\.ly)|(?:use\.my)|(?:vb\.ly)|(?:vgn\.am)|(?:vl\.am)|(?:vm\.lc)|(?:w55\.de)|(?:wapo\.st)|(?:wapurl\.co.uk)|(?:wipi\.es)|(?:wp\.me)|(?:x\.vu)|(?:xr\.com)|(?:xrl\.in)|(?:xrl\.us)|(?:xurl\.es)|(?:xurl\.jp)|(?:y\.ahoo.it)|(?:yatuc\.com)|(?:ye\.pe)|(?:yep\.it)|(?:yfrog\.com)|(?:yhoo\.it)|(?:yiyd\.com)|(?:youtu\.be)|(?:yuarel\.com)|(?:z0p\.de)|(?:zi\.ma)|(?:zi\.mu)|(?:zipmyurl\.com)|(?:zud\.me)|(?:zurl\.ws)|(?:zz\.gd)|(?:zzang\.kr)|(?:›\.ws)|(?:✩\.ws)|(?:✿\.ws)|(?:❥\.ws)|(?:➔\.ws)|(?:➞\.ws)|(?:➡\.ws)|(?:➨\.ws)|(?:➯\.ws)|(?:➹\.ws)|(?:➽\.ws))\/[a-zA-Z0-9]*/
);
if (!link.length) {
return;
}
var URL = apiBuilder + link;
var req = new XMLHttpRequest();
req.open("GET", URL, true);
req.send();
response = req.responseText;
textNode.nodeValue = v + " (" + response + " )";
};
Correct me if I'm wrong but wouldn't v.search return the matched value? I haven't messed with Javascript very often, but I'm attempting to make a chrome extension that will take any shortened URL on a page and display an unshortened version after it.
Now my regex does match the text if I test it in a regex tester, so I'm assuming my issue is the function that I'm using to set my variable "link".
Link is always empty regardless of the webpage. If I add a debug alert it always states it is empty as well, even if there is a link the regex would match.
string.search returns the first match index of the given string.If you want to get the match result and group.You should use v.match(regex).
I need to transform an xml doc into another xml doc using xslt in ie9 or above versions.
I am trying to transform an xml doc using xslt in ie9. When i used transformNode() function it is working fine in ie8(code:: resultDocument = XML.transformNode(XSL);) but in ie9 transformNode function is not defined showing error::SCRIPT438: Object doesn't support property or method 'transformNode'
I found a solution for ie9 as given below
if (window.ActiveXObject) {
console.log('inside hi');
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.loadXML(xsltDoc.xml);
console.log(xslt.styleSheet);
xslt.stylesheet = xslDoc;
var xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
return xslProc.output;
}
but when i run this i get an error: SCRIPT16389: The stylesheet does not contain a document element. The stylesheet may be empty, or it may not be a well-formed XML document.
I am new to javascript/jquery. Can anyone please help me in resolving this. If there is any other function either in javascript or jquery it would be helpful.
Thanks in advance
With earlier versions of IE the responseXML document used to be an MSXML DOM document and MSXML implements XSLT and transformNode. With newer IE versions the responseXML document gives you an IE DOM document and IE does not implement XSLT and transformNode for its DOM document/nodes. Nor does an IE DOM document have a property xml you are trying to use in xslDoc.loadXML(xsltDoc.xml);.
Try changing that part of the code to
if (typeof XMLSerializer !== 'undefined') {
xslDoc.loadXML(new XMLSerializer().serializeToString(xsltDoc));
// now use xslDoc here
}
A different option is to use xslDoc.loadXML(xmlHttp.responseText); if you still have access to the XMLHttpRequest. There is also an option to ensure you get an MSXML responseXML, see try { xhr.responseType = 'msxml-document'; } catch(e){} line in http://blogs.msdn.com/b/ie/archive/2012/07/19/xmlhttprequest-responsexml-in-ie10-release-preview.aspx.
Your whole approach to object checking in your code is wrong, check for the object or property or method you want to use (e.g. if (typeof XSLTProcessor !== 'undefined') { // now use XSLTProcessor here }), not for completely different object like document.implementation.
I too had the SCRIPT16389: The stylesheet does not contain a document element. The stylesheet may be empty, or it may not be a well-formed XML document error in IE9/10/11. I've found the following fixes it:
your code:
if (window.ActiveXObject) {
console.log('inside hi');
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.loadXML(xsltDoc.xml);
console.log(xslt.styleSheet);
xslt.stylesheet = xslDoc;
var xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
return xslProc.output;
}
working code:
if (window.ActiveXObject) {
console.log('inside hi');
var xslt = new ActiveXObject("Msxml2.XSLTemplate");
var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xslDoc.load(xsltDoc);
console.log(xslt.styleSheet);
xslt.stylesheet = xslDoc;
var xslProc = xslt.createProcessor();
xslProc.input = xmlDoc;
xslProc.transform();
return xslProc.output;
}
The change being line 6 - replace 'loadXML' with 'load' and 'xsltDoc.xml' with just 'xsltDoc'. Let me know how it goes!
I'm very beginner so I'm sorry if something doesn't make sense :)
I'm trying to search an XML DOM by ClassName, using a custom function which only seems to work when I'm searching the document the script is in.
This is the function:
Object.prototype.getElementsByClassName = function(getElementsByClass) {
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","somexml.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var foo = xmlDoc.getElementsByClassName("gridCellAlt");
(I then output foo somewhere down later - the output all works fine.)
Now, everything works if I use xmlDoc.getElementsByTagName and use a tag name - however, the page I am going to be accessing makes use of class names, so I want to use xmlDoc.getElementsByClassName. The above script works completely fine if I use var foo = document.getElementsByClassName("gridCellAlt"); and include the information I am accessing in the page running the script, but when I try to use it on the xmlDoc DOM it doesn't work. To sum it up: the only time the script doesn't work is when I'm using the xmlDoc (instead of document), and the getElementsbyClassName in conjunction. If I use document and getElementsByClassName its fine. If I use xmlDoc and get elementsByTagName its fine.
I'm thinking the getElementsByClassName isn't searching within the DOM nodes correctly, but even if I put class="gridCellAlt" somewhere in the root node of a test DOM it still doesn't find it. I've tried adding more information behind foo = xmlDoc.getElementsByClassName("gridCellAlt", (info here)) but that doesn't seem to address the issue either.
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
xmlDoc=xmlhttp.responseXML;
var foo = xmlDoc.getElementsByClassName("gridCellAlt");
}
}
Question: How do I syntax-check my XML in modern browsers (anything but IE)?
I've seen a page on W3Schools which includes an XML syntax-checker. I don't know how it works, but I'd like to know how I may achieve the same behavior.
I've already performed many searches on the matter (with no success), and I've tried using the DOM Parser to check if my XML is "well-formed" (also with no success).
var xml = 'Caleb';
var parser = new DOMParser();
var doc = parser.parseFromString(xml, 'text/xml');
I expect the parser to tell me I have an XML syntax error (i.e. an unclosed name tag). However, it always returns an XML DOM object, as if there were no errors at all.
To summarize, I would like to know how I can automatically check the syntax of an XML document using JavaScript.
P.S. Is there any way I can validate an XML document against a DTD (using JS, and not IE)?
Edit: Here is a more concise example, from MDN:
var xmlString = '<a id="a"><b id="b">hey!</b></a>';
var domParser = new DOMParser();
var dom = domParser.parseFromString(xmlString, 'text/xml');
// print the name of the root element or error message
dump(dom.documentElement.nodeName == 'parsererror' ? 'error while parsing' : dom.documentElement.nodeName);
NoBugs answer above did not work with a current chrome for me. I suggest:
var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");
dump(oDOM.getElementsByTagName('parsererror').length ?
(new XMLSerializer()).serializeToString(oDOM) : "all good"
);
You can also use the package fast-xml-parser, this package have a validate check for xml files:
import { validate, parse } from 'fast-xml-parser';
if( validate(xmlData) === true) {
var jsonObj = parse(xmlData,options);
}
Just F12 to enter developer mode and check the source there you can then search validateXML and you are to locate a very long complete XML checker for your reference.
I am using react and stuff using the DOMParser to present the error message as:
handleXmlCheck = () => {
const { fileContent } = this.state;
const parser = new window.DOMParser();
const theDom = parser.parseFromString(fileContent, 'application/xml');
if (theDom.getElementsByTagName('parsererror').length > 0) {
showErrorMessage(theDom.getElementsByTagName('parsererror')[0].getElementsByTagName('div')[0].innerHTML);
} else {
showSuccessMessage('Valid Xml');
}
}
Basic xml validator in javscript. This code may not valid for advance xml but basic xml.
function xmlValidator(xml){
// var xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
while(xml.indexOf('<') != -1){
var sub = xml.substring(xml.indexOf('<'), xml.indexOf('>')+1);
var value = xml.substring(xml.indexOf('<')+1, xml.indexOf('>'));
var endTag = '</'+value+'>';
if(xml.indexOf(endTag) != -1){
// console.log('xml is valid');
// break;
}else{
console.log('xml is in invalid');
break;
}
xml = xml.replace(sub, '');
xml = xml.replace(endTag, '');
console.log(xml);
console.log(sub+' '+value+' '+endTag);
}
}
var xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
xmlValidator(xml);
/**
* Check if the input is a valid XML file.
* #param xmlStr The input to be parsed.
* #returns If the input is invalid, this returns an XMLDocument explaining the problem.
* If the input is valid, this return undefined.
*/
export function xmlIsInvalid(xmlStr : string) : HTMLElement | undefined {
const parser = new DOMParser();
const dom = parser.parseFromString(xmlStr, "application/xml");
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString
// says that parseFromString() will throw an error if the input is invalid.
//
// https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML
// says dom.documentElement.nodeName == "parsererror" will be true of the input
// is invalid.
//
// Neither of those is true when I tested it in Chrome. Nothing is thrown.
// If the input is "" I get:
// dom.documentElement.nodeName returns "html",
// doc.documentElement.firstElementChild.nodeName returns "body" and
// doc.documentElement.firstElementChild.firstElementChild.nodeName = "parsererror".
//
// It seems that the parsererror can move around. It looks like it's trying to
// create as much of the XML tree as it can, then it inserts parsererror whenever
// and wherever it gets stuck. It sometimes generates additional XML after the
// parsererror, so .lastElementChild might not find the problem.
//
// In case of an error the <parsererror> element will be an instance of
// HTMLElement. A valid XML document can include an element with name name
// "parsererror", however it will NOT be an instance of HTMLElement.
//
// getElementsByTagName('parsererror') might be faster than querySelectorAll().
for (const element of Array.from(dom.querySelectorAll("parsererror"))) {
if (element instanceof HTMLElement) {
// Found the error.
return element;
}
}
// No errors found.
return;
}
(Technically that's TypeScript. Remove : string and : HTMLElement | undefined to make it JavaScript.)