How do I add CDATA to an xml file? - html

I have an existing xml file that holds notifications I want to display on my site. A snippet follows:
<contents>
<item>
<![CDATA[
<a style="font-weight: bold;" href="http://engadget.com">Engadget</a>
]]>
</item>
<item>
<![CDATA[
<a style="font-weight: bold;" href="http://cnn.com">CNN</a>
]]>
</item>
</contents>
I'm trying to open this document and add new "items" to it, but I can't:
foreach (string s in notifications)
{
XmlElement newElement = doc.CreateElement("item");
newElement.InnerXml = "<![CDATA[ " + s + " ]]>";
doc.DocumentElement.SelectNodes("/contents")[0].AppendChild(newElement);
}
notifications is a List that I'm using to store the links. The error I'm getting is:
']]>' is not allowed in character data.
The notifications need to contain HTML, because of the way I'm displaying it. Thanks for looking, guys.

Try using
newElement.AppendChild(doc.CreateCDataSection(s));
instead of
newElement.InnerXml = "<![CDATA[ " + s + " ]]>";

Try this way:
newElement.InnerXml = "<![CDATA[ " + s + " ]]>";

Related

Browser can not parse HTML properly - Grails 2

I am generating HTML from controller (Backend) but browser can not parse that HTML properly.
Controller code:
def getValue (returnIndex) {
String dropDown = "<select name='" + returnIndex + "' style=''>"
def CatArr = new BudgetViewDatabaseService().executeQuery("SELECT c.id,c.name AS categoryName FROM chart AS a LEFT JOIN crtClass AS b ON a.id=b.chart_class_type_id LEFT JOIN chart_group AS c ON b.id=c.chart_class_id WHERE c.status=1")
if (CatArr.size()) {
for (int i = 0; i < CatArr.size(); i++) {
def catId = CatArr[i][0]
def ProductArr
ProductArr = new BudgetViewDatabaseService().executeQuery("SELECT id,accountCode,accountName FROM bv.crtMsr where status='1' AND chart_group_id='" + catId + "'")
if (ProductArr.size()) {
dropDown += "<optgroup label='" + CatArr[i][1] + "'>"
for (int j = 0; j < ProductArr.size(); j++) {
dropDown += "<option value='" + ProductArr[j][1] + "' >" + ProductArr[j][1] + " " + ProductArr[j][2] + "</option>"
}
dropDown += "</optgroup>"
}
}
}
dropDown += "</select>"
return dropDown
}
view page's code:
<div class="fieldContainer fcCombo">
<label>
My GL <b>:</b>
</label>
${new CoreParamsHelperTagLib().getValue('formFourGLAccount')}
</div>
issue:
Generated HTML looks like:
When I am opening that HTML on edit mode from browser then its looks like:
<select name='formFourGLAccount' style=''><optgroup
label='Overige immateriële bezittingen'><option value='0430' >0430 Overige niet
materiële bezittingen</option></optgroup><optgroup label='Computers en
computerapparatuur'><option value='0210' >0210 Computers en
computerapparatuur</option><option value='0211' >0211 Afschrijving computers en
computerapparatuur</option></optgroup><optgroup label='Overige materiële
bezittingen'><option value='0250' >0250 Overige materiële
bezittingen</option><option value='0251' >0251 Afschrijving overige materiele
bezittingen</option></optgroup><optgroup label='Waarborgsommen'><option
value='0300' >0300 Waarborgsommen</option></optgroup><optgroup
label='Deelnemingen in andere bedrijven'><option value='0310' >0310 Aandeel of belang
in andere bedrijven</option></optgroup><optgroup label='Strategische langlopende
beleggingen'><option value='0320' >0320 Strategische langlopende
beleggingen</option></optgroup><optgroup label='Verstrekte langlopende leningen
(hypotheek ed)'><option value='0330' >0330 Verstrekte langlopende leningen (hypotheek
ed)</option></optgroup><optgroup label='Overige financiële
bezittingen'><option value='0340' >0340 Overige financiële bezittingen</option></optgroup><optgroup label='Voorraad'><option
If I copy returns result (HTML) from controller and past it on browser manually then its working fine
You have not shown how that HTML is being rendered so it isn't clear specifically how to fix it, but what is happening is the content is being HTML encoded, which you do not want if you want the browser to evaluate the HTML tags.
EDIT Based On Comment:
<div class="fieldContainer fcCombo">
<label>
My GL <b>:</b>
</label>
${new CoreParamsHelperTagLib().getGLAccountExpanseBudgetForReconcilationOthersDropDown('formFourGLAccount')}
</div>
There is no good reason to create an instance of a taglib. You should invoke the tag as a GSP tag.
You are returning hardcoded HTML from your controller as a model variable. That is a bad idea, but not what you are asking about. If you really do want to do that, then you will need to prevent the data from being HTML encoded in your GSP. You can use the raw(your unescaped html code here) method in your GSP as one way to avoid the encoding.

Unable to use <link> tag in Razor View

If I use the following code the view renders fine.
But if I change the url to the necessary RSS spec. the view will not render and throws an error saying that the tag is invalid so the error is occurring at the link tag. No matter what I try the link tag inside the razor foreach will not compile correctly.
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.RSsfeed>
#using ContentModels = Umbraco.Web.PublishedContentModels;
#{
Layout = null;
Response.ContentType = "text/xml";
var rootNode = Umbraco.TypedContentAtRoot().First();
var newsNodes = umbraco.uQuery.GetNodesByType("newsDetail");
}<?xml version="1.0"?>
<!-- News Aritcles -->
<rss version="2.0" xmlns:newsArticles="https://xxx.xxxxxxx.xxx/news">
<channel>
<title>News Aritcles</title>
<link>https://xxx.xxxxxxx.xxx/news</link>
<description>News Aritcles</description>
<language>en-us</language>
<ttl>1440</ttl>
#foreach(var newsNode in newsNodes){
var newsContent = UmbracoContext.Current.ContentCache.GetById(newsNode.Id);
string nnDescription = newsContent.GetPropertyValue("description").ToString();
string nnPublishDate = newsContent.GetPropertyValue("publishDate").ToString();
<item>
<title>#newsNode.Name</title>
<url>https://xxx.xxxxxxx.xxx#{#newsNode.Url}</url>
<description>#nnDescription</description>
<pubDate>#nnPublishDate</pubDate>
<guid>https://xxx.xxxxxxx.xxx#{#newsNode.Url}</guid>
</item>
}
</channel>
</rss>
<link/> is a void element, and so only has a start tag and no end tag - See W3C HTML Language Reference
You could output the tag like this
#("<link>" + newsNode.Url + "</link>")
Hope this helps

Is there a way to add a new line to display in the title attribute of an Anchor tag in HTML?

I am using this code to store HTML code in a variable called $conversions
$conversions = "GBP " . number_format($file*0.84) . "CHF " . number_format($file*1.23)
However I can't seem to figure out how to add a <br> before the word "CHF ".
Any ideas?
The whole code is as follows:
<?php
$file = get_field('fl_price');
if(trim($file) == ""){echo 'Price on Application' ;}else{$conversions = "GBP " . number_format($file*0.84) . "<br />CHF " . number_format($file*1.23) ;echo 'EUR ' . number_format($file) . "</br><a class=\"wp-tooltip\" title=\" $conversions \">Other Currencies</a>" ;}
?>
$conversions = "GBP " . number_format($file*0.84) . "
CHF " . number_format($file*1.23);
Echoing $conversions will now have a HTML-linebreak before CHF.
You are adding your string to an attribute of <a> called title. This isn't going to be displayed and is certainly not going to render any HTML (like a br tag).
edit:
As per OptimusCrime's suggestion, this does work:
http://jsfiddle.net/5rM4u/1/
Replace your <br/> with
and you're good to go.
You are trying to print the $conversions variable in the "title" of the "a" tag. just using <br /> will not work.
See some of the answers to this question "How can I use a carriage return in a HTML tooltip?" it may contain the answer that you are looking for.

Can someone add fundamental reasons why appending html markup to field variables is wrong

html += '<tr style="display:none;"><td class="leftval">ID:</td><td><span id="' + _uniqueId + '-id">' + one + '</span></td></tr>';
html += '<tr><td class="leftval"><label for="' + _uniqueId + '-itemdesc" title="This is the descriptive text that will actually appear in the email.">Description: </label></td>';
html += '<td><input value="' + four + '" class="CDinput" name="itemdesc" id="' + _uniqueId + '-itemdesc" type="text"></td></tr>';
html += '<tr><td class="leftval"><label for="' + _uniqueId + '-title" title="This is the title text that is used in the email. The text usually is used as the anchor text of a link.">Title: </label></td>';
html += '<td><input value="' + five + '" class="CDinput" name="title" id="' + _uniqueId + '-title" type="text"></td></tr>';
html += '<tr><td class="leftval"><label style="color:#f16d44;" for="' + _uniqueId + '-enddate" title="This is the expiration of the offer. The formating here is arbitrary and does not impact how the end date would look in the actual template.">End Date: </label></td>';
html += '<td><input style="width:230px" value="' + six + '" class="CDinput" name="enddate" id="' + _uniqueId + '-itemenddate" type="text">';//I'm overriding the default width for the calendar image
html += '<img style="cursor:pointer;" class="CDdate" id="' + _uniqueId + '-dateselector"src="/images/Calendar_hyperlink.png"></td></tr>';
I can think of 3 reasons:
string connector operands like ' + ' make it harder to read
Indentation is more difficult since it's awkward to indent the field to simulate a properly formatted html snippet.
Display logic is mixed in tightly with business application logic, making diversifying focus difficult.
You have 3 good reasons listed, and are in the top three. Trying to mix the two makes for ugly code, hard to read, hard to maintain, etc.
One other thing, though, that I hadn't thought of until recently, is that some editors, such as Netbeans, will tell you when your HTML is broken. Forgetting to close tags, wrong values, etc. I'm using PHP for my work, and I've gotten into the habit of doing soemthing like this:
<li>
<span class='name'><?php echo _TAG_INDEX ?>:</span>
<span class='value'><?php echo $get_zone_array['DB_ID'] ?></span>
</li>
Using it like this, if I forgot to close a tag, like if I forgot the closing </span> somewhere, it would point it out for me, so I could go in and fix it. However, if I was putting the HTML into a variable, or echoing it directly, like this:
$html = "<li><span class='name'>"._TAG_INDEX.":<span>" // notice missing / in </span>
. "<span class='value'>".$get_zone_array['DB_ID']."</span>"
. "</li>";
echo $html;
then there wouldn't be any HTML-checking from the editor, making finding those nasty little xHTML errors harder to find.
Some of the reasons:
It's butt-ugly!
It's slow. (The += operator in Java is not fast. Sometimes acceptable, but definitely not fast because it has to do a lot of object creation and buffer copying.)
It's too easy to introduce XSS vulnerabilities through strings not being properly quoted.
It's too inflexible; change anything on the layout and you have to change all the code.
Use a templating library instead. So much easier to get right.

Techniques for building HTML in code

An html template is compiled into the application as a resource. A fragment of the HTML template looks like:
<A href="%PANELLINK%" target="_blank">
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
</A><BR>
%CAPTIONTEXT%
i like it like this because the larger resource HTML file contains styling, no-quirks mode, etc.
But as is always the case, they now want the option that the Anchor tag should be omitted if there is no link. Also if there is no caption, then the BR tag should be omitted.
Considered Technique Nº1
Given that i don't want to have to build entire HTML fragments in C# code, i considered something like:
%ANCHORSTARTTAGPREFIX%<A href="%PANELLINK%" target="_blank">%ANCHORSTARTTAGPOSTFIX%
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
%ANCHORENDTAGPREFIX%</A>%ANCHORENDTAGPOSTFIX%CAPTIONPREFIX%<BR>
%CAPTIONTEXT%%CAPTIONPOSTFIX%
with the idea that i could use the pre and postfixes to turn the HTML code into:
<!--<A href="%PANELLINK%" target="_blank">-->
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
<!--</A>--><!--<BR>
%CAPTIONTEXT%-->
But that is just rediculous, plus one answerer reminds us that it wastes bandwith, and can be buggy.
Considered Technique Nº2
Wholesale replacement of tags:
%AnchorStartTag%
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
%AnchorEndTag%%CaptionStuff%
and doing a find-replace to change
%AnchorStartTag%
with
"<A href=\"foo\" target=\"blank\""
Considered Technique Nº3
i considered giving an ID to the important HTML elements:
<A id="anchor" href="%PANELLINK%" target="_blank">
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
</A><BR id="captionBreak">
%CAPTIONTEXT%
and then using an HTML DOM parser to programatically delete nodes. But there is no easy access to a trustworthy HTML DOM parser. If the HTML was instead xhtml i would use various built-in/nativly available xml DOM parsers.
Considered Technique Nº4
What i actually have so far is:
private const String htmlEmptyTemplate =
#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN\"""+Environment.NewLine+
#" ""http://www.w3.org/TR/html4/strict.dtd"">"+Environment.NewLine+
#"<HTML>"+Environment.NewLine+
#"<HEAD>"+Environment.NewLine+
#" <TITLE>New Document</TITLE>"+Environment.NewLine+
#" <META http-equiv=""X-UA-Compatible"" content=""IE=edge"">"""+Environment.NewLine+
#" <META http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">"+Environment.NewLine+
#"</HEAD>"+Environment.NewLine+
#""+Environment.NewLine+
#"<BODY style=""margin: 0 auto"">"+Environment.NewLine+
#" <DIV style=""text-align:center;"">"+Environment.NewLine+
#" %ContentArea%"+Environment.NewLine+
#" </DIV>" + Environment.NewLine +
#"</BODY>" + Environment.NewLine +
#"</HTML>";
private const String htmlAnchorStartTag =
#"<A href=""%PANELLINK%"" target=""_blank"">";
//Image is forbidden from having end tag
private const String htmlImageTag =
#"<IMG border=""0"" src=""%PANELIMAGE%"" style=""%IMAGESTYLE%"">";
private const String htmlCaptionArea =
#"<BR>%CAPTIONTEXT%";
And i already want to gouge my eyeballs out. Building HTML in code is a nightmare. It's a nightmare to write, a nightmare to debug, and a nightmare to maintain - and it will makes things difficult on the next guy. i'm hoping for another solution - since i am the next guy.
My reputation points in this game already being low gives me the freedom to tell you quite plainly that you, sir or madame, are in serious need of XSLT. Failing this (and you probably will) you need to look at XML literals in VB.NET (which provides you with the template-based solution you are looking for...). Since I prefer to stay in C# (even though I was born and raised on VBA), I use XSLT.
Both of my unwelcome recommendations require the use of XHTML instead of HTML. This requirement alone is quite a turn off to many traditional developers. I can already see through your use of capital letters for HTML elements that you will find my remarks utterly useless. So I should stop writing now.
What about this: Store XML as your fragment:
<fragment type="link_img_caption">
<link href="%PANELLINK%" />
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" />
<caption text="%CAPTIONTEXT%" />
</fragment>
Pull it out, replace the placeholders with the "real" strings (that you have carefully XML-escaped of course),
...and use a simple XML transformation to produce HTML output:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="4.0" encoding="iso-8859-1" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="fragment" />
</xsl:template>
<xsl:template match="fragment[#type = 'link_img_caption']">
<xsl:choose>
<xsl:when test="link[#href != '']">
<a href="{link/#href}" target="_blank">
<img src="{img/#src}" style="{img/#style}" border="0" />
</a>
</xsl:when>
<xsl:otherwise>
<img src="{img/#src}" style="{img/#style}" border="0" />
</xsl:otherwise>
</xsl:choose>
<xsl:if test="caption[#text !='']">
<br />
<xsl:value-of select="caption/#text" />
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Other fragment types could be added because of the type attribute. There is much room to improve this, so look at it as an example of how it could be done.
Output:
<a href="%PANELLINK%" target="_blank">
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" border="0">
</a>
<br>
%CAPTIONTEXT%
and, if the link href is empty in the XML:
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" border="0">
<br>
%CAPTIONTEXT%
Use a templating engine, like one of these.
1.) Don't use comments, you'll send useless data to the browser wasting bandwidth and encountering BUGs in IE.
2.) Would this not be better as some sort of method? (I'm not familiar with C#) but something like this makes more sense to me.
//using PHP in this example
function HTMLImage($imageData, $linkData){
var str = '';
//if there is link data, start <a> tag
$str .= '<a '.{expand any attributes}.'>';
//add image tag and attributes from $imageData
$str .= '<img '.{expand any attributes}.'/>';
//if there is link data, close <a> tag
$str .= '</a>';
return $str;
}
I would use Template Toolkit, unfortunately it is currently only implemented in Perl and Python.
test.pl:
use Template;
my $template = Template->new({
VARIABLES => {
ImageStyle => "default",
CaptionText => "Place Caption Here"
},
});
$template->process( 'test.tt', {
panel => {
link => "http://Stackoverflow.com/",
image => "/Content/Img/stackoverflow-logo-250.png",
alt => "logo link to homepage"
}
} );
test.tt:
[% IF panel.link -%]
<A href="[% panel.link %]" alt="[% panel.alt %]" target="_blank">
[%- END -%]
[%- IF panel.image -%]
<IMG border="0" src="[% panel.image %]" style="[% ImageStyle %]">
[%- END -%]
[%- IF panel.link %]</A>[% END %]<BR>
[% CaptionText %]
Outputs:
<A href="http://Stackoverflow.com/" alt="logo link to homepage" target="_blank">
<IMG border="0" src="/Content/Img/stackoverflow-logo-250.png" style="default">
</A><BR>
Place Caption Here
If the variable panel.link isn't defined it skips the anchor tags.
<IMG border="0" src="/Content/Img/stackoverflow-logo-250.png" style="default">
<BR>
Place Caption Here
Templates are a serious code smell. Take a look at how Seaside generates html.
[Edit] Another one where someone without a clue downvoted.