2014-12-05 51 views
0

我正嘗試使用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 
+0

是的,但那次我無法正確地將行添加到data.frame。解析大型XML文件時,現在遇到了問題。 – user2877232 2014-12-05 01:21:41

+0

@RichardScriven我看到了你的帖子,但它在幾天前被刪除。我已經解決了我所遇到的問題,現在又出現了這個新錯誤。你能幫忙嗎? – user2877232 2014-12-11 23:07:09

回答

0

我想這個昨天回答,並指出,在你想要的一切輸出已經在xmlT中oList輸出。你甚至可以解析下面的路徑列來獲取父類,類型和其他列。

x <- xmlParse(your sample XML with <root> tags added) 
y <- xmlToList(x) 
z <- unlist(y) 
data.frame(path=names(z), value=z) 
            path  value 
1    CATALOG.PLANT.COMMON.text Bloodroot 
2 CATALOG.PLANT.COMMON..attrs.Source   a 
3 CATALOG.PLANT.COMMON..attrs.Available  false 
4    CATALOG.PLANT.COMMON.text Columbine 
5 CATALOG.PLANT.COMMON..attrs.Source   b 
6 CATALOG.PLANT.COMMON..attrs.Available  true 
+0

謝謝你的回覆克里斯。你認爲你可以幫助我研究我目前遇到的問題嗎?我已更新我的帖子。 – user2877232 2014-12-11 23:15:05