在R中使用xpathSApply函数

时间:2015-09-12 11:52:56

标签: r

我现在正在学习R并在使用xpathSApply()时遇到这些错误。

doc=xmlTreeParse("http://www.w3schools.com/xml/simple.xml")
xpathSApply(node,"//name",xmlValue)
  Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘saveXML’ for signature       ‘"character"’

doc2=htmlTreeParse("http://espn.go.com/nfl/team/_/name/bal/baltimore-ravens")
scores=xpathSApply(doc2,"//li[@class='score]",xmlValue)
Error in UseMethod("xpathApply") : 
  no applicable method for 'xpathApply' applied to an object of class "XMLDocumentContent"

如何解决它。

2 个答案:

答案 0 :(得分:0)

请参阅xmlParsehtmlParse功能。说明:

‘xmlParse’ and ‘htmlParse’ are equivalent to the ‘xmlTreeParse’
and ‘htmlTreeParse’ respectively, except they both use a default
value for the ‘useInternalNodes’ parameter of ‘TRUE’, i.e. they
working with and return internal nodes/C-level nodes.  These can
then be searched using XPath expressions via ‘xpathApply’ and
‘getNodeSet’.

我的解决方案:

xml.file <- xmlParse( file = "http://www.w3schools.com/xml/simple.xml")

names    <- xpathSApply( doc  = xml.file
                       , path = "//name"
                       , fun  = xmlValue
                       )

[1] "Belgian Waffles"             "Strawberry Belgian Waffles"  "Berry-Berry Belgian Waffles" "French Toast"                "Homestyle Breakfast"    

然后,对于ESPN页面:

html.file  <- htmlParse( file = "http://espn.go.com/nfl/team/_/name/bal/baltimore-ravens")

scores <- xpathSApply( doc  = html.file
                     , path = "//li[@class='score']"
                     , fun  = xmlValue
                     )

list()

你的xpath表达式一定有问题,因为它没有返回任何东西:)。

答案 1 :(得分:0)

以下代码对我有用:

indexOf

使用xmlTreeParse时,您可能错过了将useInternalNodes选项设置为TRUE