为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免字符串中出现特殊字符

如何避免字符串中出现特殊字符

Go
德玛西亚99 2023-07-10 10:48:00
我正在解析包含 URL 的 XML,并且我想迭代此 XML 以获取所有 URL 并向每个 URL 发出请求,但字符串包含换行符\n。如何避免 URL 中出现新行?Go版本是go1.12.7 darwin/amd64。我有解决这个问题的方法,我只是从字符串中删除这个字符。package mainimport (    "encoding/xml"    "fmt"    "io/ioutil"    "log"    "net/http"    "strings")type SitemapIndex struct {    Locations []string `xml:"sitemap>loc"`}type NewsMap struct {    Keyword  string    Location string}type News struct {    Titles    []string `xml:"url>news>title"`    Keywords  []string `xml:"url>news>keywords"`    Locations []string `xml:"url>loc"`}func main() {    var s SitemapIndex    var n News    newsMap := make(map[string]NewsMap)    resp, _ := http.Get("https://washingtonpost.com/news-sitemaps/index.xml")    bytes, _ := ioutil.ReadAll(resp.Body)    xml.Unmarshal(bytes, &s)    for _, Location := range s.Locations {        tempURL := strings.Replace(Location, "n", "", -1) // how to avoid new lines character in url?        resp, err := http.Get(tempURL)                // do some stuff...}如果位置上没有此替换方法,我会收到错误 parsehttps://www.washingtonpost.com/news-sitemaps/politics.xml: net/url: invalid control character in URLexit status 1以下是示例 XML 文件https://www.washingtonpost.com/news-sitemaps/politics.xml
查看完整描述

1 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

XML 文本包含 Dave C 在评论中提到的换行符。由于 URL 中不允许出现换行符,因此您必须删除换行符。

通过用“”替换换行符(而不是n)来修复。注意反斜杠。

tempURL := strings.Replace(Location, "\n", "", -1)

更好的解决方法是使用 strings.TrimSpace (Dave C 也提到过)。这将处理文件中可能存在的所有无关空白:

tempURL := strings.TrimSpace(Location)


查看完整回答
反对 回复 2023-07-10
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信