在xml属性中的查询字符串中的&符号

时间:2016-03-11 12:08:03

标签: c# xml

在HTML属性中编码URL时,我遇到了一个奇怪的问题。

我有以下HTML:

<a href=" https://www.google.co.in/#q=Pune&tbm=nws"></a>

到目前为止一切正常。

但是,此HTML是使用XmlTextWriter动态生成的。

因此代码生成以下XML

<a href=" https://www.google.co.in/#q=Pune&amp;tbm=nws"></a>

注意&amp;之后的Pune 单击此链接时,浏览器无法解码tbm=nws参数。

我阅读了几篇文章,似乎表明上面的第二个HTML完全有效。

你能指导我哪里出错吗?

编辑:添加C#代码

 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();  

1 个答案:

答案 0 :(得分:1)

我认为你在这里正在攻击错误的问题。 &符号可以(并且应该)在HREF标记中转义。有关详细信息,请参阅此问题:Do I encode ampersands in <a href...>?

查询字符串的前缀应该是。使用的客户端框架时,这可能不明确,但规则仍然适用。

尝试按照以下格式设置锚点:

<a href="https://www.google.co.in/#/?q=Pune&amp;tbm=nws"></a>
相关问题