R - 简单的XML解析

时间:2013-02-07 00:42:05

标签: xml r xml-parsing

假设我在下面运行了代码:

url.df_1 = htmlTreeParse(url_1, useInternalNodes = T)

并得到htmlTree:

           <!-- ******************* related ******************* --> 
    <div class="more-related-box">

    <div id="app_related">
        <h3>Customers Also Bought</h3>
            <ul>
<li><a href="/app/ios/flick-golf/" title="Flick Golf!"><img src="http://a2.mzstatic.com/us/r1000/067/Purple/v4/25/a8/91/25a891df-fed4-9dc4-0d86-1c8f5acf893f/mzl.fcctkywr.75x75-65.jpg" class="app_icon"><span class="app_name">Flick Golf!</span><span class="category">Games</span></a></li>

              <li><a href="/app/ios/minecraft-pocket-edition/" title="Minecraft – Pocket Edition"><img src="http://a1.mzstatic.com/us/r1000/070/Purple2/v4/3f/56/07/3f56074b-af27-8ba3-7ef8-c97314c13ee7/mzl.rfhcaysw.75x75-65.jpg" class="app_icon"><span class="app_name">Minecraft – Pocket Edition</span><span class="category">Games</span></a></li>

我想从上面抓到的是“flick-golf”和“minecraft-pocket-edition”。 (所以上面是htmltree的一部分,我想抓住这些名称,并希望最终将它们作为列表或数据框。)

到目前为止,我尝试了这个(以及其他一些人)

getNodeSet(url.df_1, "//div[@id = 'app_related']//h3 ")

但我最终得到了

[[1]]
<h3>Customers Also Bought</h3> 

attr(,"class")

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您需要确保您的xml格式正确。我假设你会照顾它。在那之后你只需要正确的XPath争论,在你的情况下将是//li/a/@title

> str <- '<div class="more-related-box">
+ <div id="app_related">
+ <h3>Customers Also Bought</h3>
+ <ul>
+ <li>
+ <a href="/app/ios/flick-golf/" title="Flick Golf!">
+ <img src="http://a2.mzstatic.com/us/r1000/067/Purple/v4/25/a8/91/25a891df-fed4-9dc4-0d86-1c8f5acf893f/mzl.fcctkywr.75x75-65.jpg" class="app_icon" />
+ <span class="app_name">Flick Golf!</span>
+ <span class="category">Games</span>
+ </a>
+ </li>
+ <li>
+ <a href="/app/ios/minecraft-pocket-edition/" title="Minecraft – Pocket Edition">
+ <img src="http://a1.mzstatic.com/us/r1000/070/Purple2/v4/3f/56/07/3f56074b-af27-8ba3-7ef8-c97314c13ee7/mzl.rfhcaysw.75x75-65.jpg" class="app_icon" />
+ <span class="app_name">Minecraft – Pocket Edition</span>
+ <span class="category">Games</span>
+ </a>
+ </li>
+ </ul>
+ </div>
+ </div>'
> doc <- xmlParse(str)
> getNodeSet(doc, "//li/a/@title")
[[1]]
        title 
"Flick Golf!" 
attr(,"class")
[1] "XMLAttributeValue"

[[2]]
                         title 
"Minecraft – Pocket Edition" 
attr(,"class")
[1] "XMLAttributeValue"

attr(,"class")
[1] "XMLNodeSet"