2016-09-29 64 views
1

我想從數據庫中的xml FDA標籤中提取成分列表。不知何故,我無法獲得getNodeSet函數來生成適當的節點列表。R:從深層嵌套的XML文件中將XML節點值提取到數據框中

問題:如何解決代碼能夠提取成分名稱的值。

這是不起作用的代碼,它在getNodeSet函數中斷開,給出0長度列表。我在this answer (flatten xml)上嘗試了[有禮貌地提出]解決方案,還有許多人沒有運氣。

library(XML) 
URL <- "http://www.accessdata.fda.gov/spl/data/e9b9a189-d9e3-42e3-b41c-846a94ebeb37/e9b9a189-d9e3-42e3-b41c-846a94ebeb37.xml" 
xmlDocu <- xmlParse(URL) 
xmlIngredients <- getNodeSet(xmlDocu, "//ingredient/ingredientSubstance/name") 
Ingredients <- xmlSApply(xmlIngredients, function(x) xmlSApply(x, xmlValue)) 
dfIngredients <- data.frame(t(Ingredients),row.names=NULL) 

這是從深度嵌套的xml文件的部分權益的樣子:

   <ingredient classCode="ACTIB"> 
        <quantity> 
         <numerator value="160" unit="mg"/> 
         <denominator value="5" unit="mL"/> 
        </quantity> 
        <ingredientSubstance> 
         <code code="362O9ITL9D" codeSystem="2.16.840.1.113883.4.9"/> 
         <name>Acetaminophen</name> 
         <activeMoiety> 
         <activeMoiety> 
          <code code="362O9ITL9D" codeSystem="2.16.840.1.113883.4.9"/> 
          <name>acetaminophen</name> 
         </activeMoiety> 
         </activeMoiety> 
        </ingredientSubstance> 
       </ingredient> 
       <ingredient classCode="IACT"> 
        <ingredientSubstance> 
         <code code="3QPI1U3FV8" codeSystem="2.16.840.1.113883.4.9"/> 
         <name>BUTYLPARABEN</name> 
        </ingredientSubstance> 
       </ingredient> 

回答

2

我相信你的問題是有關在XML文件中定義的命名空間。這是解決這個問題的幾種方法。我寧願是用XML2包,帶出的命名空間,然後解析文件:

library(xml2) 

URL <- "http://www.accessdata.fda.gov/spl/data/e9b9a189-d9e3-42e3-b41c-846a94ebeb37/e9b9a189-d9e3-42e3-b41c-846a94ebeb37.xml" 
xmlDocu <- read_xml(URL) 
#find namespace 
ns<-xml_ns(xmlDocu) 

#I find it easier to strip the name space and use accordingly 
xml_ns_strip(xmlDocu) 
xml_find_all(xmlDocu, "//ingredient") 
xml_text(xml_find_all(xmlDocu, "//ingredient/ingredientSubstance/name")) 

我找到rvest的語法和XML2更容易使用,則XML封裝。