Синтаксический анализ XML возвращает строку с символами новой строки. - PullRequest
0 голосов
/ 02 февраля 2019

Я пытаюсь проанализировать XML с помощью карты сайта, а затем перебрать адрес, чтобы получить подробные сведения о записи в Go.Но я получаю эту странную ошибку:

: первый сегмент пути в URL не может содержать двоеточие

Это фрагмент кода:

type SitemapIndex struct {
    Locations []Location `xml:"sitemap"`
}

type Location struct {
    Loc string `xml:"loc"`
}

func (l Location) String() string {
    return fmt.Sprintf(l.Loc)
}

func main() {
    resp, _ := http.Get("https://www.washingtonpost.com/news-sitemaps/index.xml")
    bytes, _ := ioutil.ReadAll(resp.Body)
    var s SitemapIndex
    xml.Unmarshal(bytes, &s)
    for _, Location := range s.Locations {
        fmt.Printf("Location: %s", Location.Loc)
        resp, err := http.Get(Location.Loc)
        fmt.Println("resp", resp)
        fmt.Println("err", err)
    }
}

И вывод:

Location: 
https://www.washingtonpost.com/news-sitemaps/politics.xml
resp <nil>
err parse 
https://www.washingtonpost.com/news-sitemaps/politics.xml
: first path segment in URL cannot contain colon
Location: 
https://www.washingtonpost.com/news-sitemaps/opinions.xml
resp <nil>
err parse 
https://www.washingtonpost.com/news-sitemaps/opinions.xml
: first path segment in URL cannot contain colon
...
...

Я предполагаю, что Location.Loc возвращает новую строку до и после актуального адреса.Например: \nLocation: https://www.washingtonpost.com/news-sitemaps/politics.xml\n

Поскольку URL-адрес жесткого кодирования работает должным образом:

for _, Location := range s.Locations {
        fmt.Printf("Location: %s", Location.Loc)
        test := "https://www.washingtonpost.com/news-sitemaps/politics.xml"
        resp, err := http.Get(test)
        fmt.Println("resp", resp)
        fmt.Println("err", err)
    }

Выведите, как вы видите, ошибка равна nil:

Location: 
https://www.washingtonpost.com/news-sitemaps/politics.xml
resp &{200 OK 200 HTTP/2.0 2 0 map[Server:[nginx] Arc-Service:[api] Arc-Org-Name:[washpost] Expires:[Sat, 02 Feb 2019 05:32:38 GMT] Content-Security-Policy:[upgrade-insecure-requests] Arc-Deployment:[washpost] Arc-Organization:[washpost] Cache-Control:[private, max-age=60] Arc-Context:[index] Arc-Application:[Feeds] Vary:[Accept-Encoding] Content-Type:[text/xml; charset=utf-8] Arc-Servername:[api.washpost.arcpublishing.com] Arc-Environment:[index] Arc-Org-Env:[washpost] Arc-Route:[/feeds] Date:[Sat, 02 Feb 2019 05:31:38 GMT]] 0xc000112870 -1 [] false true map[] 0xc00017c200 0xc0000ca370}
err <nil>
Location: 
...
...

Но яЯ очень новичок в Go, и поэтому я понятия не имею, что не так.Не могли бы вы сказать мне, где я не прав?

Ответы [ 2 ]

0 голосов
/ 02 февраля 2019

См. Комментарии, встроенные в измененный код, для описания и устранения проблемы

func main() {
    resp, _ := http.Get("https://www.washingtonpost.com/news-sitemaps/index.xml")
    bytes, _ := ioutil.ReadAll(resp.Body)
    var s SitemapIndex
    xml.Unmarshal(bytes, &s)
    for _, Location := range s.Locations {
            // Note that %v shows that there are indeed newlines at beginning and end of Location.Loc
            fmt.Printf("Location: (%v)", Location.Loc)
            // solution: use strings.TrimSpace to remove newlines from Location.Loc
            resp, err := http.Get(strings.TrimSpace(Location.Loc))
            fmt.Println("resp", resp)
            fmt.Println("err", err)
    }

}

0 голосов
/ 02 февраля 2019

Вы действительно правы, проблема в новых строках.Как видите, вы используете Printf без добавления каких-либо \n, и один добавляется в начале, а один в конце в выводе.

Вы можете использовать strings.Trim чтобы удалить эти новые строки.Вот пример работы с картой сайта, которую вы пытаетесь проанализировать.Как только строка обрезана, вы сможете без ошибок вызвать http.Get.

func main() {
    var s SitemapIndex
    xml.Unmarshal(bytes, &s)

    for _, Location := range s.Locations {
        loc := strings.Trim(Location.Loc, "\n")
        fmt.Printf("Location: %s\n", loc)
    }
}

Этот код правильно выводит местоположения без каких-либо символов новой строки, как и ожидалось:

Location: https://www.washingtonpost.com/news-sitemaps/politics.xml
Location: https://www.washingtonpost.com/news-sitemaps/opinions.xml
Location: https://www.washingtonpost.com/news-sitemaps/local.xml
Location: https://www.washingtonpost.com/news-sitemaps/sports.xml
Location: https://www.washingtonpost.com/news-sitemaps/national.xml
Location: https://www.washingtonpost.com/news-sitemaps/world.xml
Location: https://www.washingtonpost.com/news-sitemaps/business.xml
Location: https://www.washingtonpost.com/news-sitemaps/technology.xml
Location: https://www.washingtonpost.com/news-sitemaps/lifestyle.xml
Location: https://www.washingtonpost.com/news-sitemaps/entertainment.xml
Location: https://www.washingtonpost.com/news-sitemaps/goingoutguide.xml

Причина появления этих новых строк в поле Location.Loc заключается в XML, возвращаемом этим URL.Записи следуют за этой формой:

<sitemap>
<loc>
https://www.washingtonpost.com/news-sitemaps/goingoutguide.xml
</loc>
</sitemap>

И, как вы можете видеть, есть новые строки до и после содержимого в элементах loc.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...