我正在尝试从他们数据库中的 xml FDA 标签中提取成分列表。不知何故,我无法使用 getNodeSet
函数来生成适当的节点列表。
问题:如何修复代码以便能够提取成分名称的值。
这是不起作用的代码,它在 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>
最佳答案
我相信您的问题与 xml 文件中定义的 namespace 有关。有几种方法可以解决这个问题。我更喜欢使用 xml2 包并去掉 namespace ,然后解析文件:
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 包更容易使用。
关于R:从深度嵌套的 XML 文件中将 XML 节点值提取到数据帧中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39761141/