在 R 中,如何遍历重复的 XML 节点并将文本值保存在列表中? [英] In R, how can I loop over repeated XML nodes, and save text values in a list?

查看:18
本文介绍了在 R 中,如何遍历重复的 XML 节点并将文本值保存在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理来自 Clinicaltrials.gov 的 XML 文件,其结构如下:

I'm working with XML files from clinicaltrials.gov, which have a structure like this:

<clinical_study>
  ...
  <brief_title>
  ...
  <location>
    <facility>
      <name>
      <address>
        <city>
        <state>
        <zip>
        <country>
    </facility>
  </location>
  <location>
    ...
  </location>
  ...
</clinical_study>

我正在从多个 XML 文件中收集信息,因此每个文件中的位置数未知,甚至可能为零.我需要提取有关每个位置的所有信息并保存到 SQL 表中.我使用 XML 包中的函数从单个节点中提取信息取得了一些成功,例如

I'm gathering information from multiple XML files, so the number of locations in each file is unknown and could even be zero. I need to extract all the information about each location and save into an SQL table. I've had some success using functions from the XML package to extract information from single nodes, e.g.

library(XML)
nct_url <- "http://clinicaltrials.gov/ct2/show/NCT00112281?resultsxml=true"
xml_doc <- xmlParse(nct_url, useInternalNode=TRUE)
title_path <- "/clinical_study/brief_title" 
title_text <- xpathSApply(xml_doc, title_path, xmlValue)

我正在尝试使用 getNodeSet,这给了我一组正确的长度:

I'm experimenting with getNodeSet, and this gives me a set of the right length:

doc <- xmlParse("NCT00007501.xml")
locations <- getNodeSet(doc, "/clinical_study/location")
length(locations)
[1] 22
> class(locations)
[1] "XMLNodeSet"

但是我从这个集合中提取信息的尝试大多没有结果.有什么建议吗?

but my attempts to extract information from this set have been mostly fruitless. Any suggestions?

推荐答案

这是一个例子

 ns <- getNodeSet(xml, '//clinical_results/outcome_list/outcome/analysis_list/analysis/method')
 element_cnt <-length(ns))
 strings<-paste(sapply(ns, function(x) { xmlValue(x) }),collapse="|"))

这篇关于在 R 中,如何遍历重复的 XML 节点并将文本值保存在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆