简体   繁体   English

R 使用 XML2 从 XML 提取数据到 dataframe

[英]R extract data from XML to dataframe using XML2

I am new to R.我是 R 的新手。 Trying to parse data from an XML into a dataframe.试图将 XML 中的数据解析为 dataframe。

I need a dataframe with columns:我需要一个带有列的 dataframe:

MAC, device_Online_status, device_onine_threshold, device_online_value. MAC、device_Online_status、device_onine_threshold、device_online_value。

Was able to coerce the first one.能够胁迫第一个。 I cannot seem to get the last three tags.我似乎无法获得最后三个标签。

Code so far:到目前为止的代码:

library(xml2)
library(tidyverse)
library("stringr")

test_xml <- read_xml("test.xml")

xml_name(test_xml)
xml_name(xml_parent(test_xml))
xml_name(xml_children(test_xml))

# print the full path directory:

test_xml %>% xml_find_all( '//*') %>% xml_path()
test_xml %>% xml_find_all( '//GW_RESPONSE/*') %>% xml_path()

test_xml %>% xml_find_all('//ONLINE_STATUS/*') %>% xml_path()

# device name extracted to a vector
device_name <- test_xml %>% xml_find_all( '//GW_RESPONSE/*') %>% xml_path()
## device_name <- substr(device_name, nchar(device_name) - 12 + 1, nchar(device_name))
device_name <- str_sub(device_name, -12, -1)

The following snippets show me the data I want:以下片段向我展示了我想要的数据:

xml_find_first(test_xml, "//ONLINE_STATUS")

output: output:

<DEVICE_ONLINE_STATUS id="DEVICE_ONLINE_STATUS" status="FAIL" threshold="UP" value="DOWN"/>

Any way to get this output into a vector or a dataframe?有什么方法可以将此 output 转换为向量或 dataframe?

Thanks.谢谢。

SAMPLE XML:样品 XML:

<SQV>
<RESPONSE id="RESPONSE" value="RESPONSE"><GW_RESPONSE id="GW_RESPONSE" status="" threshold="" value=""><GATEWAY_1056117CA4AE id="GATEWAY_1056117CA4AE" status="" threshold="" value=""><ONLINE_STATUS id="ONLINE_STATUS" value=""><DEVICE_ONLINE_STATUS id="DEVICE_ONLINE_STATUS" status="FAIL" threshold="UP" value="DOWN"/></ONLINE_STATUS><DEVICE_STATUS id="DEVICE_STATUS" status="FAIL" threshold="" value="FAIL"/></GATEWAY_1056117CA4AE></GW_RESPONSE></RESPONSE>
</SQV>

SOLVED:解决了:

xml_attrs() and xml_attr() xml_attrs() 和 xml_attr()

Get you to the needed data.让您获得所需的数据。

eg例如

xml_find_all(test_xml, "//DEVICE_ONLINE_STATUS") %>% xml_attrs() xml_find_all(test_xml, "//DEVICE_ONLINE_STATUS") %>% xml_attrs()

or或者

xml_find_all(test_xml, "//DEVICE_ONLINE_STATUS") %>% xml_attr("id") xml_find_all(test_xml, "//DEVICE_ONLINE_STATUS") %>% xml_attr("id")

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

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