4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gofeedを使って、パースできないUnicode文字を除去してパースする方法

Posted at

背景

gofeedのParseURLメソッドでwebページをパースしようとしたところ、以下のエラーが発生。
不正文字(パースできないUnicode文字)がXML上に含まれているとのこと。

  XML syntax error on line 650: illegal character code U+0008
  panic: runtime error: invalid memory address or nil pointer dereference
  exit status 2

エラーが起きるたびに不正文字を置換で除くのは大変なので、不正文字を除去してパースする仕組みにしたい。

環境

  • Golang 1.11.0
  • gofeed v1.0.0-beta2

対応

ParseURLメソッドだと、webページに不正文字が存在する時点でエラーになってしまうため、以下の手順を踏むことで対応する。

  1. webページをstring型で取得
  2. unicode.IsPrintstrings.Mapを利用し、不正文字を除去
  3. ParseStringメソッドでパース

修正前

main.go
  func main() {
      fp := gofeed.NewParser()
      feed, _ := fp.ParseURL(パース対象のwebページのURL) // ParseURLでエラー
      items := feed.Items
      ...
  }

修正後

main.go
  func main() {
      resp, _ := http.Get(blog.URL)
      defer resp.Body.Close()
      body, _ := ioutil.ReadAll(resp.Body)
      xmlData := strings.Map(printOnly, string(body))

      fp := gofeed.NewParser()
      feed, _ := fp.ParseString(xmlData)
      items := feed.Items
      ...
  }

  func printOnly(r rune) rune {
      if unicode.IsPrint(r) {
          return r
      }
      return -1
  }

※エラーハンドリングは省略

参考

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?