我正嘗試使用Duncan Temple Lang的XML包解析R中的XML。該函數的目標是解析給定的XML數據並在data.frame中生成輸出,如下面所需的輸出所示。 getValues函數用於生成屬性名稱及其相關值的列表,然後在調用時將其傳遞到數據框中。但它不會這樣工作,因爲並非所有的屬性名稱和值都出現在數據框中。請參閱下面的示例XML和我正在獲取的輸出。在數據框中顯示已解析的XML
library(XML)
getValues <- function(x) {
aList <- list()
#attributes
if(!is.null(xmlAttrs(x))) {
num.attributes = xmlSize(xmlAttrs(x))
for (i in seq_len(num.attributes)) {
attributeName <- names(xmlAttrs(x)[i])
attributeValue <- xmlAttrs(x)[[i]]
aList <- append(aList, c(Name = attributeName, Text = attributeValue))
}
}
return(aList)
}
retrieveStructureInfo <- function(node) {
if (is.null(node)) {
return()
}
nkids <- xmlSize(node)
bypass <- function(n = nkids) {
if(nkids == 0) {
xpathApply(xmlParent(node), path = xpath, fun = getValues)
} else {
return(nkids)
}
}
#children is the no. of nodes within a node
for (i in 1 : children) {
#recursive function call
retrieveStructureInfo(node[[i]])
}
}
#parse xml document
#xmlfile is the file path
doc <- xmlParse(xmlfile)
r <- xmlRoot(doc)
data <- data.frame(node = NA, value = NA)
retrieveStructureInfo(r)
data
示例XML:
<CATALOG>
<PLANT>
<COMMON Source="a" Available="false">Bloodroot</COMMON>
<LOCATION></LOCATION>
<PARENT />
</PLANT>
<PLANT>
<COMMON Source="b" Available="true">Columbine</COMMON>
<LOCATION>Africa</LOCATION>
<PARENT />
</PLANT>
</CATALOG>
輸出:
node value
source a
source b
所需的輸出:
node value
source a
available false
source b
available true
是的,但那次我無法正確地將行添加到data.frame。解析大型XML文件時,現在遇到了問題。 – user2877232 2014-12-05 01:21:41
@RichardScriven我看到了你的帖子,但它在幾天前被刪除。我已經解決了我所遇到的問題,現在又出現了這個新錯誤。你能幫忙嗎? – user2877232 2014-12-11 23:07:09