在rss中解码两次转义的标题

huangapple go评论70阅读模式
英文:

Unescape twice escaped title in rss

问题

我得到了一些带有奇怪转义标题的RSS,例如:

<title>S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC</title>

整个RSS链接:https://www.dailyfx.com/francais/feeds/actualites-marches-financiers

Opera浏览器正确显示这样的新闻标题如下:

> S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une
> enquête de la SEC

对于我通常接收到的一次转义的新闻和上述情况,我应该如何正确取消转义新闻标题?

英文:

I got some rss with strange escaped titles, for example:

<title>S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC</title>

the whole rss: https://www.dailyfx.com/francais/feeds/actualites-marches-financiers

opera browser shows such news titles correctly as follows

> S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une
> enquête de la SEC

How can I correctly unescape news for the case normally I receive once-escaped news, and for the case above?

答案1

得分: 2

序列&编码了一个&符号。但是,如果内容应该是HTML,那么它可能包含进一步的HTML转义序列。

例如,如果要显示的文本包含&,在HTML中它将被编码为&。如果将此文本插入XML中,第一个字符&也必须被转义,结果是&

要获取可读的解码文本,您需要解析XML并将其解码为HTML。您可以使用html.UnescapeString()

例如:

const src = `<title>S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC</title>`

var s string
if err := xml.Unmarshal([]byte(src), &s); err != nil {
	panic(err)
}
fmt.Println(s)

s = html.UnescapeString(s)
fmt.Println(s)

这将输出(在Go Playground上尝试):

S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC
S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC
英文:

The sequence & encodes a & sign. But if the content ought to be HTML for example, that may contain further HTML escape sequences.

For example if the text to display contains &, in HTML it would be encoded as &. If you insert this text into an XML, the first character & also has to be escaped which results in &.

To get the human-readable decoded text, you have to parse the XML and decode as HTML. You may use html.UnescapeString().

For example:

const src = `<title>S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC</title>`

var s string
if err := xml.Unmarshal([]byte(src), &s); err != nil {
	panic(err)
}
fmt.Println(s)

s = html.UnescapeString(s)
fmt.Println(s)

This will output (try it on the Go Playground):

S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC
S&P 500 : Wall Street amorce un rebond, Binance fait l'objet d'une enquête de la SEC

huangapple
  • 本文由 发表于 2022年6月8日 16:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/72542424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定