Reputation: 561
I am facing a strange problem when encoding a URL in an HTML Attribute.
I have the following HTML:
<a href=" https://www.google.co.in/#q=Pune&tbm=nws"></a>
This works fine so far.
However this HTML is generated dynamically using XmlTextWriter
.
Hence the code generates the following XML
<a href=" https://www.google.co.in/#q=Pune&tbm=nws"></a>
Note the &
after Pune
When this link is clicked the browser is unable to decode the tbm=nws
parameter.
I read several articles which seemed to suggest that the second HTML above is perfectly valid.
Can you guide me on where could this be going wrong?
EDIT: Adding C# code
XmlTextWriter writer = new XmlTextWriter (Console.Out);
writer.Formatting = Formatting.Indented;
// Write the root element.
writer.WriteStartElement("Items");
// Write a string using WriteRaw. Note that the special
// characters are not escaped.
writer.WriteStartElement("Item");
writer.WriteAttributeString("href","https://www.google.co.in/#q=Pune&tbm=nws");
writer.WriteString("Write unescaped text: ");
writer.WriteRaw("this & that");
writer.WriteEndElement();
// Write the same string using WriteString. Note that the
// special characters are escaped.
writer.WriteStartElement("Item");
writer.WriteString("Write the same string using WriteString: ");
writer.WriteString("this & that");
writer.WriteEndElement();
// Write the close tag for the root element.
writer.WriteEndElement();
// Write the XML to file and close the writer.
writer.Close();
Upvotes: 0
Views: 731
Reputation: 2982
I think you are attacking the wrong problem here. Ampersands can (and should) be escaped in HREF tags. See this question for more details: Do I encode ampersands in <a href...>?
The Query string should really be prefixed with ?. This can be ambiguous when using client side frameworks that use #, but the rules still apply.
Try formatting your anchor like this:
<a href="https://www.google.co.in/#/?q=Pune&tbm=nws"></a>
Upvotes: 1