JavaScript parse XML - javascript

I try to parse an XML string and have some problems. Here is my current state.
I have a Cordova app which reads QR-Codes (with the BarcodeScanner plugin). The QR-Code holds the XML information. When I read the code, I want to print out the XML code. Here is what I tried (the important part):
var app = {
output: null,
xmlDoc: null,
// this function is called when I click a button
scanCode: function(){
//first parameter is a callback, which is called when a barcode is detected
cordova.plugins.barcodeScanner.scan(
function (result) {
alert(result.text);
var parser = new DOMParser();
**app.xmlDoc = parser.parseFromString(result.text,"text/xml");**
app.output = document.getElementById("codeInfo");
app.traverse(app.xmlDoc.documentElement, "");
},
function (error) {
alert("Scanning failed: " + error);
}
);
},
traverse: function(node, offset){
if(node.nodeType == 3){
app.output.innerHTML += "<b>" + offset + node.nodeValue + "</b><br>";
}else{
app.output.innerHTML += offset + node.nodeName + "<br>";
var childs = node.childNodes;
for(var i=0; i<childs.length; i++){
app.traverse(childs[i], offset + " ");
}
}
}
};
My XML code looks something like this
<node><child1>text1</child1><child2>text2</child2></node>
So I expect an output like:
node
child1
text1
child2
text2
But I always get something like:
html
body
parsererror
h3
This page contains the following errors:
...
When I use a static text like
var xml = "<node><child1>text1</child1><child2>text2</child2></node>"
and use this instead of 'result.text' in the marked line, everything works as expected.
So maybe the 'result.text' is just a reference and not the value? Could this be the problem? I'm not an expert so how can I solve this problem?
P.S.: The XML code I get from the QR-Code is correct and well formed.

app.xmlDoc = parser.parseFromString(result.txt,"text/xml");
should actually be:
app.xmlDoc = parser.parseFromString(result.text,"text/xml");
There is an "e" missing in result.text

After reading Valencia's comment and the "wrong" output again and think about it, I figured out what's wrong. So the "wrong" output is just an error message in HTML format, where i print every tag. The message itself says:
This page contains the following errors:
error on line 1 at column 14: String not started expectin ' or "
The beginning should look like this
<?xml version="1.0" encoding="UTF-8"?>
but when creating the QR-Code backslashes are added
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
The first backslash is at column 14.
When I create a static XML string I insert backslashes to mask the ' " ', so my declaration and the XML code from the QR-Code look equal. But they aren't, cause the static XML string does not contain the backslashes. And these backslashes cause the error while parsing.
The easiest solution is to just not put the XML information in the QR-Code. So directly starting with the first node.
Thanks for your help.

Related

Storing multi line html encoded string into sql

I want to store html code into sql database which I've encoded by using encodeURI() but it showing me multiple errors as below
I'm using dataType as <CLOB> also tried using NVARCHAR(MAX) but is showing same error.
Sharing my encoded html code below in string format tobe store into sql.
%3Cp%3Ethis%20kind%20of%20text%20i'm%20storing%20into%20database%3C/p%3E%3Cpre%20class=%22code-pre%22%3Evar uri%20= %22my%20test.asp?name=st%C3%A5le&car=saab%22;%0Avar enc%20=%20encodeURI(uri);%0Avar dec%20=%20decodeURI(enc);%0Avar res%20=%20enc%20+ %22<br>%22 +%20dec;%0A%3C/pre%3E
INSERT INTO "Mytable" VALUES(
8/*ID <INTEGER>*/,
'Return matching objects from array of objects'/*QUESTION <NVARCHAR(200)>*/,
'%3Cp%3Ethis%20kind%20of%20text%20i'm%20storing%20into%20database%3C/p%3E%3C pre%20class=%22code-pre%22%3Evar uri%20= %22my%20test.asp ?
name=st%C3%A5le&car=saab%22;%0Avar enc%20=%20encodeURI(uri);%0Avar
dec%20=%20decodeURI(enc);%0Avar res%20=%20enc%20+ %22<br>%22
+%20dec;%0A%3C/pre%3E'/*QUESTION_DESC <CLOB>*/,
'20170508'/*CREATED <TIMESTAMP>*/,
0/*USERID <INTEGER>*/,
1/*TAGID <INTEGER>*/
);
Above command i'm using for pushing data to db. QUESTION_DESC string i've encoded.original string is
<p>this kind of text i'm storing into database</p><pre class="code-
pre">var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = enc + "<br>" + dec;
</pre>
Help will be appriciated
This was quite simple when i tried posting html code from middle ware.
The problem is when i tried to post an html code to database it was showing error because of some random double quotes. So while sending that html code from middle ware i just replaced the double quotes to ignore double quotes. i did like
my html code to be stored in db
var htmlCodeToBeStored =
"<p>this kind of text i'm storing into database</p><pre class="code-
pre">var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = enc + "<br>" + dec;
</pre>"
I replaced above string with as below
htmlCodeToBeStored = htmlCodeToBeStored.replace(/"/g, "\"")
with that simple change i'm able to store my ans into data base.

google apps script spreadsheet string retrieving issue

I can't figure out why the following code isn't working properly in case of special characters:
[...]
// get strings (names) from spreadsheet
var persons = SpreadsheetApp.getActiveSheet().getRange(2, 1, 31, 4).getValues();
// for each row
for (var row in persons) {
// build the filename
var myFile = persons[row][1] + "_" + persons[row][0] + "_20180124.txt";
[...]
// handle from Google Drive only file
var driveFiles = DriveApp.getFilesByName(myFile);
while (driveFiles.hasNext()) {
var file = driveFiles.next();
if(driveFiles.getName() == myFile) {
/* write to Log
Saša_KLANJŠČEK_20180124.txt not written
Peter_MARINČIČ_20180124.txt not written
Peter_KLANJŠČEK_20180124.txt not written
Niko_ČERNIC_20180124.txt not written
Tjaša_KOGOJ_20180124.txt written
*/
Logger.log(myFile + "\n");
[...]
Strings with uppercase unicode characters causes the conditional statement to fail. I tried with toString("UTF-8") method, but it still doesn't work. Is it an encoding problem?
Change:
if(driveFiles.getName() == myFile) {
into
if(file.getName() == myFile) {

HTML string gets extra newline character if sent from server to client

I'm having trouble with string manipulation. I have some code written in java, that will use an xls translator to generate some html for me - in string form.
I use spring framework to communicate this string back to my web code, but when the string arrives in the javascript, it fails with an "invalid or unexpected token error. Furthermore, when the string is written to the console, it seems that the string now containts newline characters for each new tag.
For my javascript I really need the html to be all one line.
here are some code bits:
try {
SimpleResultSet rs = dbClient.executeQuery("select MediaContent from call where id = " + callID);
if (rs.next()) {
media = rs.getString("MediaContent");
mimeType = rs.getString("MediaTypeID");
if(media.startsWith("<?xml")) {
trace.info("XSLT: " + xltString);
trace.info("Database XML: " + media);
media = Transform(media, xltString, response);
//trace.info("result HTML: " + media);
if (!media.isEmpty()) {
media = media.replaceAll("\n\r", "")
.replaceAll("\n", "")
.replaceAll(System.lineSeparator(), "");
}
}
//media = media.replaceAll("\"","\\\\\"");
}
} catch (DBException e) {
trace.warning("Failed to get call content media for call id = " + callID, e);
return media;
}
trace.info("cleaned HTML: " + media);
return media == null ? "" : media;
}
At this point the trace printing out the cleaned HTML, shows the string all on one line, without any newline characters. The string is then propagated to the ModelAndView like this:
return new ModelAndView("media", "media", mediaStr);
and on the javascript side:
<script>
var contentString = "${media}";
document.getElementById("mediaContentIFrame").srcdoc = contentString;
it is the contentString variable on the javascript side that fails with the invalid or unexpected token error.
The contentString is used to initialise the srcdoc property of an IFrame.
You have already added two checks \r\n and \n.. Also add \r and i hope it will start working :)

c# HtmlAgilityPack and Yahoo's HTML

So I am goofing off and wrote something that first queries other websites and loads all of the pertinent stock exchange symbols and the tries to iterate through the symbols and load Yahoo's server for the latest stock price. For some reason no matter what I try to search by using HtmlAgilityPack, I can't seem to get any pertinent info back. I don't think there's an issue with some javascript running after the page is loaded (but I could be wrong).
The following is a generalized routine that can be tinkered with to try and get the percentage change of the stock symbol back from Yahoo:
string symbol = "stock symbol"
string link = #"http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=" + symbol;
string data = String.Empty;
try
{
// keep in this scope so wedget and doc deconstruct themselves
var webget = new HtmlWeb();
var doc = webget.Load(link);
string percGrn = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-up']");
string percRed = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-down']");
// create somthing we'll nuderstand later
if ((String.IsNullOrEmpty(percGrn) && String.IsNullOrEmpty(percRed)) ||
(!String.IsNullOrEmpty(percGrn) && !String.IsNullOrEmpty(percRed)))
throw new Exception();
// adding string to empty gives string
string perc = percGrn + percRed;
bool isNegative = String.IsNullOrEmpty(percGrn);
double percDouble;
if (double.TryParse(Regex.Match(perc, #"\d+([.])?(\d+)?").Value, out percDouble))
data = (isNegative ? 0 - percDouble : percDouble).ToString();
}
catch (Exception ex) { }
finally
{
// now we need to check what we have and load into the datgridView
if (!newData_d.ContainsKey(symbol)) newData_d.Add(symbol, data);
else MessageBox.Show("ERROR: Duplicate stock Symbols for: " + symbol);
}
And here is the extended method for FindInnerHtml:
// this is for the html agility class
public static string FindInnerHtml( this HtmlAgilityPack.HtmlDocument _doc, string _options)
{
var node = _doc.DocumentNode.SelectSingleNode(_options);
return (node != null ? node.InnerText.ToString() : String.Empty);
}
Any help with getting something back would be appreciated, thanks!
///////////////////////////////////////
EDIT:
///////////////////////////////////////
I highlighted the span id and then check out line 239 for where I saw 'yfi-price-change-up' reference:
The following XPath successfully find the target <span> which contains percentage of increase (or decrease) :
var doc = new HtmlWeb().Load("http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=msft");
var xpath = "//span[contains(#class,'time_rtq_content')]/span[2]";
var span = doc.DocumentNode.SelectSingleNode(xpath);
Console.WriteLine(span.InnerText);
output :
(0.60%)

JSON and Backslash

Can anyone shed any light as to why my JSON is coming out below, with the extra backslashes. I am using ASP.net MVC to serialise a datatable, when I debug in Visual studio it all looks ok but when I look with firebug with adds the extra characters?
Any ideas anyone?
JSON
[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\",\"first_name\":\"Daniel\",\"last_name\":\"James\",\"fql_query_response_Id\":0,\"LIFEID\":null}
JAVASCRIPT
function GetFBFriends() {
FB.Connect.requireSession(function() {
$.ajax({
url: "/Facebook/GetFaceBookFriends",
type: 'POST',
data: null,
dataType: 'json',
success: function(result) {
data = "<table>";
alert(result.length);
for (i = 0; i < result.length; i++) {
data += "<tr><td><td><img src=" + result[i].pic + " alt=" + result[i].first_name + " /></td><input type='checkbox' value='" + result[i].uid + "' name='friends[]' id = 'friend" + result[i].uid + "' /></td><td>" + result[i].first_name + " " + result[i].last_name + "</td></tr>";
}
data += "</table>";;
}
});
})
};
Public Function GetFaceBookFriends() As JsonResult
Dim fbFriends As New DataTable
Try
fbFriends = FacebookModel.GetFriendsAndMatchToLife()
Return Json(JsonConvert.SerializeObject(fbFriends))
Catch ex As Exception
Finally
fbFriends.Dispose()
fbFriends = Nothing
End Try
End Function
That's Firebug showing the string containing JSON in it's string representation. Think of it as JSON-encoding a string containing JSON. Or rather, if your were to put the JSON in a string literal in your Javascript, it would look like that.
Your string does not actually contain those backslashes. They are just escapes for the double-quotes.
Looks like Firebug is adding escape characters. What if you enclosed your entire JSON in single quotes? That may correct the problem. Edit Can you provide the code that encodes your JSON?
I solved this question, I was returning JSON data which was then being changed into JSON by jquery as well, so I simply returned a string and jquery handled it correctly.
I would suggest doing injecting the following into the first line for the success function.
console.dir({'result':result});
This will show you what you are getting back, as opposed to just viewing the result from the network call.
The Firebug display is simply escaping the string, so you can copy/paste the entire result into the console for inspection/interrogation directly...
var temp = {pasted-string-here}
//var temp = "[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\", ... }]"
var val = JSON.parse(temp);
console.debug({"val":val});

Categories