登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-16 17:54:29 398浏览 收藏

在处理包含 URL 的 XML 文件时,需要避免出现特殊字符,例如换行符 (\n)。换行符会使 URL 无效,导致无法发出请求。 为了解决这个问题,可以在解析 XML 之前,使用字符串替换或修剪函数从 URL 中删除换行符。一种方法是使用 strings.Replace() 函数,如下所示: ```go tempURL := strings.Replace(Location, "\n", "", -1) ``` 另一种更简洁的方法是使用 strings.TrimSpace() 函数,它可以同时删除前后空白和换行符: ```go tempURL := strings.TrimSpace(Location) ``` 通过使用这些方法,可以有效地从 URL 中删除换行符,从而确保 URL 有效且可以用于发出请求。

问题内容

我正在解析包含 url 的 xml,并且我想迭代此 xml 以获取所有 url 并向每个 url 发出请求,但字符串包含换行符 \n。如何避免 url 中出现新行?

go版本是go1.12.7 darwin/amd64。我有解决这个问题的方法,我只是从字符串中删除这个字符。

package main

import (
    "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...
}

如果位置上没有此替换方法,我会收到错误 parse https://www.washingtonpost.com/news-sitemaps/politics.xml : net/url: url 中的控制字符无效 退出状态 1

这里是示例 xml 文件 https://www.washingtonpost.com/news-sitemaps/politics.xml


解决方案


xml 文本包含 dave c 在评论中提到的换行符。由于 url 中不允许出现换行符,因此您必须删除换行符。

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

tempurl := strings.replace(location, "\n", "", -1)

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

tempURL := strings.TrimSpace(Location)

好了,本文到此结束,带大家了解了《如何避免字符串中出现特殊字符》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>