2013-05-15 34 views
2

當我嘗試解析xml/html文檔的某個屬性時,出現奇怪的編碼問題。 這裏重複的例子,含有2個標題2項(注意這裏使用法國口音的)解析xml屬性:奇怪編碼問題

library(XML) 
doc <- htmlParse('<note> 
       <item title="é">1</item> 
       <item title="ï">3</item> 
      </note>',asText=TRUE,encoding='UTF-8') 

現在使用xpathApply,我能讀懂我的項目是這樣。請注意,特殊的口音在這裏格式良好。

xpathApply(doc,'//item') 

[[1]] 
<item title="é">1</item> 

[[2]] 
<item title="ï">3</item> 

但是當我嘗試閱讀我的屬性稱號,我得到這個:

xpathApply(doc,'//item',xmlGetAttr,'title') 
[[1]] 
[1] "é" 

[[2]] 
[1] "ï" 

我試過其他的XPath版本一樣:

xpathApply(doc,'//item/@title') 
    xmlAttrs(xpathApply(doc,'//item')[[1]]) 

但是,這是行不通的。請幫忙嗎?

+0

這對我很好。 R 3.0.0 i686-pc-linux-gnu – user1609452

+1

在windows上,這個錯誤是可重現的。 – user1609452

+0

當被誤解爲ISO 8859-1或windows-1252編碼數據時,字符串「Ã」和「Ã」是UTF-8編碼的「é」和「ï」的表示。 –

回答

2

它不漂亮,我不能測試這臺Linux機器上,但嘗試:

xpathApply(doc,'//item', 
     function(x) iconv(xmlAttrs(x,'title'), "UTF-8", "UTF-8")) 
[[1]] 
title 
    "é" 

[[2]] 
title 
    "ï" 

xmlAttrs電話RS_XML_xmlNodeAttributes研究這個代碼似乎是處理編碼沒有設施。 xmlValue調用R_xmlNodeValue這添加了編碼。看看?xmlValue我們有encoding: experimental functionality and parameter related to encoding.也許以後會添加屬性的編碼。

+0

來自@Jukka K. Korpela評論可能對 – user1609452

+0

有幫助謝謝!我測試它,它工作。我只是簡化你的答案。這裏不需要使用'lapply'。 – agstudy

+0

與樂隊的好點;) – user1609452