RSS 中的 URL 编码链接会破坏链接

Cho*_*hoy 5 xml rss urlencode

为了获得有效的 XML RSS 提要,我需要对查询字符串中包含“&”的链接进行 url 编码。但是,当用户在浏览器中查看 RSS 源时,链接不会被解码,因此当他们单击链接时,结果页面会被破坏,因为查询字符串参数没有被正确读取。

例如

http://www.mysite.com?foo1=bar1&foo2=bar2,在浏览器中查看为http://www.mysite.com?foo1=bar1%26foo2=bar2时,参数 foo1 被视为 bar1%26foo2 =bar2 而不是将水果和饮料分成两个单独的参数。

将我的链接包装在标签中而不对其进行编码是可行的,但是在我的 MRSS 提要中,我有一些字段,例如包含标签会破坏 XML。

我怎样才能正确编码我的链接以便一切正常?

Con*_*rix 4

简短回答

使用&amp

长答案

如果您查看https://stackoverflow.com/feeds/tag/xml,这个问题的条目看起来像这样,并且您的示例链接在 IE 中查看时工作正常

您的示例链接

http://www.mysite.com?foo1=bar1&foo2=bar2

您的参赛作品

<entry>
        <id>/sf/ask/399367251/</id>
        <re:rank scheme="http://stackoverflow.com">0</re:rank>
        <title type="text">URL encoded links in RSS breaks links</title>
        <category scheme="https://stackoverflow.com/feeds/tag/xml/tags" term="xml"/><category scheme="https://stackoverflow.com/feeds/tag/xml/tags" term="rss"/><category scheme="https://stackoverflow.com/feeds/tag/xml/tags" term="urlencode"/>
        <author>
            <name>Choy</name>
            <uri>/sf/users/17677061/</uri>
        </author>
        <link rel="alternate" href="/sf/ask/399367251/" />
        <published>2011-04-18T15:30:11Z</published>
        <updated>2011-04-18T15:35:43Z</updated>
        <summary type="html">
            &lt;p&gt;In order to have a valid XML RSS feed, I need to url encode my links which contain &#39;&amp;amp;&#39; in the query string.  However, when a person views the RSS feed in a browser, the links are not decoded, so when they click on the link the resulting page is broken because the query string parameters are not being read correctly.&lt;/p&gt;

&lt;p&gt;E.g.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://www.mysite.com?foo1=bar1&amp;amp;foo2=bar2&quot; rel=&quot;nofollow&quot;&gt;http://www.mysite.com?foo1=bar1&amp;amp;foo2=bar2&lt;/a&gt;, when viewed in the browser as &lt;a href=&quot;http://www.mysite.com?foo1=bar1%26foo2=bar2&quot; rel=&quot;nofollow&quot;&gt;http://www.mysite.com?foo1=bar1%26foo2=bar2&lt;/a&gt;, the parameter foo1 is being taken as bar1%26foo2=bar2 instead of splitting fruit and drink into two separate parameters.&lt;/p&gt;

&lt;p&gt;Wrapping my links in  tags and not encoding them work, but then in my MRSS feed I have fields such as  where including a  tag breaks the XML.&lt;/p&gt;

&lt;p&gt;How can I go about correctly encoding my links so that everything works?&lt;/p&gt;

        </summary>
    </entry>
Run Code Online (Sandbox Code Playgroud)