use*_*rJT 12 xml r xml-parsing
我什么时候想要使用xmlParse
函数而不是xmlTreeParse
函数?此外,何时参数值useInternalNodes=TRUE
或asText=TRUE
有用?
例如:
library("XML")
nct_url <- "http://clinicaltrials.gov/ct2/show/NCT00112281?resultsxml=true"
xml_doc <- xmlParse(nct_url, useInternalNodes=TRUE)
Run Code Online (Sandbox Code Playgroud)
与
doc <- xmlTreeParse(getURL(nct_url), useInternalNodes=TRUE)
top <- xmlRoot(doc)
top[["keyword"]]
xmlValue(top[["start_date"]])
xmlValue(top[["location"]])
Run Code Online (Sandbox Code Playgroud)
人们似乎xmlTreeParse
通过$ doc $ children $ ...遍历使用该函数获取非重复节点.但我不确定每种方法最好的时候都能理解.解析XML是几乎放弃R并学习Python的原因之一.在没有被迫买书的情况下缺乏傻瓜的例子.
ags*_*udy 14
这里有一些使用XML包后的反馈.
xmlParse
是xmlTreeParse
where参数useInternalNodes
设置为TRUE的版本.xmlTreeParse
.如果您只想提取xml文档的部分部分,这可能不是非常有效和不必要的.xmlParse
.但是你应该知道xpath
操纵结果的一些基础.asText=TRUE
,如果你有一个文本不是一个文件或URL作为输入.这里是一个示例,我展示了两个函数之间的区别:
txt <- "<doc>
<el> aa </el>
</doc>"
library(XML)
res <- xmlParse(txt,asText=TRUE)
res.tree <- xmlTreeParse(txt,asText=TRUE)
Run Code Online (Sandbox Code Playgroud)
现在检查2个对象:
class(res)
[1] "XMLInternalDocument" "XMLAbstractDocument"
> class(res.tree)
[1] "XMLDocument" "XMLAbstractDocument"
Run Code Online (Sandbox Code Playgroud)
您看到res是内部文档.它是指向C对象的指针.res.tree是一个R对象.你可以得到这样的属性:
res.tree$doc$children
$doc
<doc>
<el>aa</el>
</doc>
Run Code Online (Sandbox Code Playgroud)
对于资源,你应该使用一个有效的xpath
要求和论文功能之一(xpathApply
,xpathSApply
,getNodeSet
),以检查它.例如:
xpathApply(res,'//el')
Run Code Online (Sandbox Code Playgroud)
一旦你创建了一个有效的XML节点,你可以申请xmlValue
,xmlGetAttr
..提取节点的信息.所以这两个陈述是等价的:
## we have already an R object, just apply xmlValue to the right child
xmlValue(res.tree$doc$children$doc)
## xpathSApply create an R object and pass it to
xpathSApply(res,'//el',xmlValue)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11285 次 |
最近记录: |