2012-07-31 38 views
3

我有一個問題,其中xmlValue條,我需要保持(或轉化爲某些其它字符,我可以然後strsplit<br />標籤防止`xmlValue`從汽提<br />標籤

下面是一個例子:

> f <- htmlParse(getForm("http://sites.target.com/site/en/spot/store_locator_popups.jsp", ajax="true", storeNumber=1889), asText=TRUE) 
> xpathSApply(f, "//div[@class=\"sl_results_popup_address\"]", xmlValue) 
[1] "1154 S Clark StChicago, IL 60605(312) 212-6300" 

對戰它解析HTML:

<div class="sl_results_popup_address"> 
1154 S Clark St 
<br/> 
Chicago, IL 60605 
<br/> 
(312) 212-6300 
</div> 

我試過, recursive=FALSE BU這似乎沒有幫助。

如果他們是<p></p>換行符,那麼它會更容易,因爲我可以單獨抓住他們,但<br/>沒有包裝文本我真的不能走這個方向。希望在xmlValue(或者<br/>正在剝離文檔解析階段?)內只有一個選項可以降低剝離級別?

回答

5

兩件事情可以幫助

app.data<-getForm("http://sites.target.com/site/en/spot/store_locator_popups.jsp", ajax="true", storeNumber=1889) 
app.data<-gsub("<br>","\n",app.data) 
f <- htmlParse(app.data, asText=TRUE) 
out<-xpathSApply(f, "//div[@class=\"sl_results_popup_address\"]", xmlValue) 
> xpathSApply(f, "//div[@class=\"sl_results_popup_address\"]", xmlValue) 
[1] "1154 S Clark St\nChicago, IL 60605\n(312) 212-6300" 
> 

所以只用別的東西代替br標籤,或者如果你想保持標籤使用原來的代碼和

> xpathSApply(f, "//div[@class=\"sl_results_popup_address\"]/text()", xmlValue) 
[1] "1154 S Clark St" "Chicago, IL 60605" "(312) 212-6300" 
> 

dum.fun<-function(x){if(xmlName(x)=="br"){"<br/>"}else{xmlValue(x)}} 
xChild<-xpathSApply(f, "//div[@class=\"sl_results_popup_address\"]",xmlChildren) 
lapply(xChild,dum.fun) 
> unlist(lapply(xChild,dum.fun)) 
[1] "1154 S Clark St" "<br/>"    "Chicago, IL 60605" 
[4] "<br/>"    "(312) 212-6300" 
> 
+0

兩個可愛的方案。謝謝。我沒有想過text()。仍然習慣xpath。很多學習,一如既往。 – 2012-07-31 14:27:12

+0

我從FireBug複製了代碼,所以也許這就是差異的來源。 – 2012-07-31 15:51:22