【问题标题】:fix xml file with invalid characters, Invalid xmlChar value 2 [9]修复带有无效字符的 xml 文件,无效的 xmlChar 值 2 [9]
【发布时间】:2021-10-30 19:21:21
【问题描述】:

我正在解析来自 web 服务的 xml 文件,偶尔会遇到此错误:

xml2:::read_xml.raw(rs$content) # where the object rs is the response from the webservice, obtained using the httr package

Error in read_xml.raw(x, encoding = encoding, ...) : 
  xmlParseCharRef: invalid xmlChar value 2 [9]

我下载了数千个 xml,只有少数损坏了。 '

我的问题是:

如何定位导致错误的响应中的字符。 修复由无效 xmlChars 引起的无效 xml 的一般策略是什么?

我已经通过将响应解析为 html 来解决问题,但我宁愿修复问题并解析为 xml

谢谢!

【问题讨论】:

    标签: r xml httr xml2


    【解决方案1】:

    我可以通过执行以下操作来弄清楚:

    首先了解 httr 响应的内容

    xml_broken <- readBin(rs$content, what = "character")
    

    然后我能够系统地从损坏的xml中删除数据,直到我终于找到导致问题的这个文本字符串:

    "&#x2;" # from the context i could see that this should be parsed as the danish character 'æ'
    

    来自https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references 我可以看到这实际上应该被编码为

    "aelig;"
    

    所以最后httr内容可以通过做解析

    rs$content %>% 
      readBin(what = "character") %>% 
      gsub(pattern = "&#x2;", replacement = "aelig;") %>%
      XML::xmlParse()
    

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 2018-10-18
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2018-07-09
      • 2013-03-18
      • 2016-11-08
      • 2018-10-21
      相关资源
      最近更新 更多