防止'xmlValue`剥离<br />标签

Ari*_*man 3 xml parsing r

我遇到了一个问题,其中xmlValue剥离了<br />我需要保留的标签(或转换为我可以继续strsplit使用的其他角色.

这是一个例子:

> 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"
Run Code Online (Sandbox Code Playgroud)

与它解析的HTML相比:

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

我试过了,, recursive=FALSE但似乎没有帮助.

如果他们是<p></p>断线然后它会更容易,因为我可以单独抓住它们,但<br/>没有包装文本我真的不能去那个方向.希望只有一个选项来降低内部完成的剥离级别xmlValue(或者<br/>在解析文档阶段可能会剥离s?).

shh*_*its 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"
>
Run Code Online (Sandbox Code Playgroud)

所以只需用br其他东西替换标签或使用原始代码即可

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

如果你想保留标签

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" 
>
Run Code Online (Sandbox Code Playgroud)