我正在解析包含 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)
- 1 回答
- 0 關注
- 163 瀏覽
添加回答
舉報
0/150
提交
取消