繁体   English   中英

如何将xml数据转换为R中的数据帧

[英]How to convert xml data to data frame in R

大家好,我需要将一个xml文件加载到R中的数据框中.xml格式如下所示。 我如何实现同样的目标?

         <?xml version="1.0" encoding="utf-8"?><posts>  <row Id="1" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/></posts>

我尝试了以下代码....它没有给出所需的输出。 我期待一个表格输出,其中列名称及其值列在下面。

library(XML)
xml.url ="test.xml"
xmlfile = xmlTreeParse(xml.url)

class(xmlfile)
xmltop=xmlRoot(xmlfile)

print(xmltop)[1:2]

plantcat <- xmlSApply(xmltop, function(x) xmlSApply(x, xmlValue))

plantcat_df <- data.frame(t(plantcat))
xml.text <- 
'<?xml version="1.0" encoding="utf-8"?>
<posts>  
<row Id="1" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="2" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="3" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="4" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
</posts>'

library(XML)
xml <- xmlParse(xml.text)
result <- as.data.frame(t(xmlSApply(xml["/posts/row"],xmlAttrs)),
                        stringsAsFactors=FALSE)
#   Id PostTypeId AcceptedAnswerId            CreationDate Score
# 1  1          1               17 2010-07-26T19:14:18.907     6
# 2  2          1               17 2010-07-26T19:14:18.907     6
# 3  3          1               17 2010-07-26T19:14:18.907     6
# 4  4          1               17 2010-07-26T19:14:18.907     6

这比平常有点棘手,因为数据是属性,而不是节点(节点是空的),所以我们不能使用xlmToDataFrame(...)

上面的所有数据仍然是字符,因此您仍然需要将列转换为适当的类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM