XML parsing of a variable string in JavaScript
Update: For a more correct answer see Tim Down's answer.
Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.
A really basic example is:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.
Extract a value from an XML string using JavaScript
First parse the XML into a DOM: see for example Parse XML using JavaScript
Then, on the resulting DOM Document object, execute the XPath expression
//entry[. = 'Function Message']/@id
This will return a set of attribute nodes.
parse XML string using javascript
Are you sure that your xmlDoc2.getElementsByTagName("row")
has at least one result? Else, the syntax seems to be fine.
Also, there's much initialisation missing in your script snippet, without which we won't be able to help you.
xmlDoc2
- is this an well-parsed XML document object (or an error message?)TotalSheetNodes
is what?mysheet
seems to be an HTML element?- what is
JCell
? It seems not to be related to the question.
EDIT:
To traverse (seems to be the right word, not "parse") your XML document you should loop through each NodeList on its own. Thats possible, every element inherits the Node interface, not only the xml document object - as you seem to believe.
Also, you should not have to count the row
s, as you are only interested in c
s. A big mistake seems to be the aritmethic approximation for the number of c
s in your (whole) document by multilpying the number or rows with the number of c
elements in the first row - your xml source proves this is wrong.
var rows = xmlDoc2.getElementsByTagName("row");
for (var i=0, l=rows.length; i<l; i++) {
var row = rows[i];
var cs = row.getElementsByTagName("c");
for (var j=0, m=cs.length; j<m; j++) {
var c = cs[j];
var t = c.getAttribute("t");
var v = c.getElementsByTagName("v")[0]; // throws an error if there is no "v"
// do whatever you want with row, c, t and v
}
}
As you don't use row
in your example above, you might just omit the outer loop and use
var cs = xmlDoc2.getElementsByTagName("c");
XML parsing of a variable string in JavaScript
Update: For a more correct answer see Tim Down's answer.
Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.
A really basic example is:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.
Parsing a string into JS language as well as parsing string into json or xml
Hopefully, I have solved this problem and I want to share knowledge with you.
this is the code to get a variable as a JS function:
var fucnsExprScript1 = document.createElement('script');
fucnsExprScript1.appendChild(document.createTextNode(`let funcExpr = [(x => NaN)]`));
document.body.appendChild(fucnsExprScript1);
function generateJSfunction(text){
let func = `funcExpr.push(x => ${text});`;
let fucnsExprScript2 = document.createElement('script');
fucnsExprScript2.textContent = func;
document.body.appendChild(fucnsExprScript2);
fucnsExprScript2.remove();
return funcExpr[funcExpr.length - 1];
}
How to parse xml using javascript?
I'm not one to throw jQuery out there, but in this case it does a good job. Check out jQuery's parseXML()
function. It returns an easy to use jQuery object to play with.
Parsing a variable containing xml string in xslt
Got it working !
Used xmlns:saxon="http://saxon.sf.net/" extension for xslt2.0 and it works perfectly to parse the xml string in the variable like below.
<xsl:value-of select="saxon:parse($SpecificOrderDetails)/SPECIFICORDERDETAILS/ORDERROW[ACTION ='0']"/>
Thanks everyone for helping!
Parse XML using JavaScript
I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.
If your XML is in a string variable called txt
and looks like this:
<address>
<street>Roble Ave</street>
<mtfcc>S1400</mtfcc>
<streetNumber>649</streetNumber>
<lat>37.45127</lat>
<lng>-122.18032</lng>
<distance>0.04</distance>
<postalcode>94025</postalcode>
<placename>Menlo Park</placename>
<adminCode2>081</adminCode2>
<adminName2>San Mateo</adminName2>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<countryCode>US</countryCode>
</address>
Then you can parse the XML with Javascript DOM like this:
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);
}
And get specific values from the nodes like this:
//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;
//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;
//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
JSFiddle
Feb. 2019 edit:
In response to @gaugeinvariante's concerns about xml with Namespace prefixes.
Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:
NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt
txt = `
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>
<s:street>Roble Ave</s:street>
<sn:streetNumber>649</sn:streetNumber>
<p:postalcode>94025</p:postalcode>
</address>`;
//Everything else the same
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);
}
//The prefix should not be included when you request the xml namespace
//Gets "streetNumber" (note there is no prefix of "sn"
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
//Gets Street name
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);
//Gets Postal Code
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
Related Topics
Insert HTML into View from Angularjs Controller
How to Deep Merge Instead of Shallow Merge
Calling Functions With Settimeout()
How to Enumerate the Properties of a JavaScript Object
Updating a Nested Array With Mongodb
How to Work Around JavaScript'S Parseint Octal Behavior
Modifying a Copy of a JavaScript Object Is Causing the Original Object to Change
How to Detect Idle Time in JavaScript
Executing ≪Script≫ Elements Inserted With .Innerhtml
Do You Recommend Using Semicolons After Every Statement in JavaScript
How May I Reference the Script Tag That Loaded the Currently-Executing Script
Convert String to Title Case With JavaScript
Difference Between Call and Apply
How to Create an Object Property from a Variable Value in JavaScript