Javascript converts XML characters to &LT and &GT - javascript

I am currently using DYMO Label Printing software to print labels. I have previously had the label XML template stored as plain text and it worked fine. But recently I have decided to move to a more dynamic approach so that labels can be edited and modified directly from the database.
So I am currently storing the XML label templates in a simple SQL database table. I set up the viewmodel that contains the XML information, and then access it in Javascript when printing in the View itself.
I previously just tried this:
try {
var labelXml = "#Viewmodel.XMLString"; //Open XML from Viewmodel directly
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
And that did not work.
I did some research and also tried this (placing viewmodel in "text/plain") and then accessing it above.
<script>
try {
var labelXml = $('#label_XML').text();
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
</script>
<script id="label_XML" type="text/plain">
#Viewmodel.XML
</script>
Both of these methods result in this: (<> replaced with &lt and &gt)
How can I simply access a XML string in the database from the viewmodel while avoiding any unwanted conversions? Thanks.
Using #Html.Raw results in this problem:
The first line is read correctly but with each line break it reads as code instead of text. I put the original #Html.Raw in quotes, is there a way to prevent it from attempting to read it as code as shown above?

It looks like you are struggling with HTML Encoding. Have you tried using #Html.Raw(Viewmodel.XML)? That helper should prevent MVC from HTML encoding the content.
Depending on where that XML content comes from, you might be creating an XSS risk, so be careful how you use Html.Raw and consider reading more about it if it does solve this problem for you Is there a risk in using #Html.Raw?

Related

Render javascript that stored in database

I have in the database table just one column and it's content either javascript link like
<script src="some src"></script>
or javascript code like
<script>
some code
<script>
So my question is it possible to correct render that javascript inside cshtml file?
You can use the Html.Raw method in your view
#model YourViewModel
#Html.Raw(Model.YourScriptContent)
Assuming YourScriptContent is the property of your view model on which you are setting the script content value, in your GET action.
public ActionResult Index()
{
var vm = new YourViewModel();
vm.YourScriptContent = "<script>alert('testing');</script>";
return View(vm);
}
By default, razor will HTML encode the return value of any c# code/expression with the prefix #. But the Raw method will return the markup which is not HTML encoded, which is what you need in this case.
Since you are not HTML encoding when you render it, I am hoping you completely trust the script content values :). Read about script injection attacks if you do not follow the previous statement.

How to present an XML file in HTML format in different ways, according to user input?

I have an XML file consisting of book nodes, and each book contains 1-4 authors, 1 title & 1 Year
I've also created an XSL file related to the above XML file so that whenever I open the XML file in a browser, its contents are presented in a html table format consisting of 3 rows "Author","Title","Year"
What I want to do now is create an HTML file that will present the above table but not all of its contents, only the ones asked through user input (appropriate fields for user input should be found on that same html file as well I guess..)
e.g. a user can type in the name of an author, or a year, or a title, or a word contained in a title or in an author's name and then have the appropriate table presented to him.
I'm a new to all this so my questions are the following :
Will I have to mess with the content in the XML and XSL files again or should I leave them intact from now on and only deal with the html file I'll be creating?
In order to achieve what I want what should my html file contain? Javascript functions that will be presenting only parts of the XML file but always according to the XSL file? Will I be using XSLT in the html file again or simply javascript?
What I need is to create smth that will take input from the user (javascript?) and then use a parser (XSLT?) to parse through the XML according to the user's input? and then return the result on screen filtered through the XSL template I created??
Could someone please indicate me the process I should follow step by step (not in detail but in which order should I deal with all the issues involved in this..) ?
Thank you very much for your understanding and help! I know there's lots of information on w3schools but the problem is that everything is fragmented and I still don't know how to combine all that, in which order and which method to choose!
btw. I don't want to use jquery for this, only XML,XSLT,XPATH,HTML,Javascript standards..
You need to pass the user-wanted processing as parameter(s) to the transformation.
Read about the xsl:param instruction.
External parameters to the transformation can be any globally declared (children of the top element xsl:stylesheet) xsl:param elements.
The way the invoker of the XSLT transformation specifies the values for these parameters on invoking the transformation is implementation - dependent and varies from one XSLT processor to another. You need to read the documentation of the particular XSLT processor for the exact information how to do this.
For example, if the XSLT processor is the .NET XslCompiledTransform, the way to pass parameters to the transformation is via the XsltArgumentList.AddParam() method.
You need to load the XSL and XML files to the javascript, you can use ajax requests for that, and you can use an iframe to load them for you. Once you have them in javascript you can use XPath and XSLT to do exactly what you want.
For example, here's a simple way to load an xml and then use XPath on it using the iframe way, it uses the input value to query the xml:
<html>
<head>
<title> xml test </title>
<script type="text/javascript">
var xml = null;
function getXml(path) {
document.getElementById("loader").src = path;
}
function loaded(frm) {
if (frm.contentWindow) {
xml = frm.contentWindow.document;
}
}
function query() {
var value = document.getElementById("query").value;
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate("//" + value,
xml,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null);
console.log(result.singleNodeValue);
}
</script>
</head>
<body>
Query the xml: <input type="text" id="query" />
<input type="button" value="Go" onclick="query()" />
<iframe style="width: 0px; height: 0px; display: none;" id="loader" onload="loaded(this)"></iframe>
<script type="text/javascript">
getXml("index.xml");
</script>
</body>
As for the XSLT part, here's a tutorial for how to do that: XSLT - On the Client. In this tutorial they also show how to load the files using ajax.
You can of course load the XSL file just like the XML one in my example.

Create a textfile from the input of an html-form with the browser (client-side)

I have an html site with a form in it and I want the user to be able to create a text/xml file depending on the input. But I wan't to avoid setting up a webserver only for this task.
Is there a good way, to do that, e.g. with Javascript? I think you can't create files with Javascript, but maybe create a data url and pass the text, so the user can save it to file?
Or is there another way to achieve this simple task without a webserver?
Solved it, somehow. I create a data url data:text/xml;charset=utf-8, followed by the XML.
function createXML() {
var XML = 'data:text/xml;charset=utf-8,<MainNode>';
var elements = document.getElementsByTagName('input'),i;
for (i in elements) {
if (elements[i].checked == true) {
XML += elements[i].value;
}
}
XML += '</MainNode>';
window.open(XML);
}
So the url looks like data:text/xml;charset=utf-8,<MainNode><SubNode>...</SubNode>...</MainNode>
Unfortunately this doesn't work for me on Chromium(Chrome) and on Firefox. It just displays the XML instead of showing a save dialog. But I think that's because of my settings and at least you can save it as a XML-file manually.
I haven't tried this but it should work.
After getting form data, system will call page A.
page A will have javascript that gets query strings and builds the page accordingly.
After finishing page build, user can save current page with following statement in javascript
document.execCommand('SaveAs',true,'file.html');

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

jQuery, Ajax and getting a complete html structure back

I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes.
I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like <,>, etc get replaced with the escaped ones
I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean.
I'm sending something like this
<results><table id="test"><tr>test</tr></table></results>
what shows up on my page if I do a page source view is this.
<results><table....
so you can see the special characters are getting converted and I don't know how to stop it.
The idea is for the <results></results> to be the xml tag and the text of that tag to be what gets placed into an existing <div> on my page.
Here is the JavaScript that I'm using to pull down the response and inserts:
$.post(url, params, function(data)
{
$('#queryresultsblock').text(data)
}, "html");
I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the html method of jQuery.
Your result:
<table id="test"><tr>test</tr></table>
Your Javascript call:
$.post(url, params, function(data){ $('#queryresultsblock').html(data) })
Another solution with less control — you can only do a GET request — but simpler is to use load:
$("#queryresultsblock").load(url);
If you must return your result in a results XML tag, you can try adding a jQuery selector to your load call:
$("#queryresultsblock").load(url + " #test");
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go.
One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send
<results><results><table....
And the javascript would convert the < to < and such.
The other option, and what I would do, is to use JSON instead of XML.
{'results': "<table id="test"><tr>test</tr></table>" }
The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
The other thing you could do is create an external .html file with just your HTML code snippet in it. So create include.html with
<results><table id="test"><tr>test</tr></table></results>
As the contents, then use a jquery .load function to get it onto the page. See it in action here.

Categories