我有一个xml文档,它的结构如下
<ClassificationNode>
<District id = "8">
<code>1A</code>
<Name>LALD1</Name>
<Zone id = "21254">
<E1>OU29</E1>
</Zones>
</District>
<ClassificationNodeChildList count = "2">
<ClassificationNode>
<District id = "8.1">
<code>1B</code>
<Name>LALD1A</Name>
<Zone id = "213">
<E1>OU54</E1>
</Zones>
</District>
<District id = "8.2">
<code>1C</code>
<Name>LALD1C</Name>
<Zone id = "214">
<E1>OU65</E1>
</Zones>
</District>
</ClassificationNode>
</ClassificationNodeChildList>
</ClassificationNode>我想得到一个看起来像这样的数据框:
district_id code Name Zone_id E1
8 1A LALD1 21254 OU29
8.1 1B LALD1A 213 OU54
8.2 1B LALD1B 214 OU65 如果可能的话,我想避免循环。这看起来很简单(很可能是这样),但我被难住了。
我试过了:
library(rvest)
library(tidyverse)
x <- "pathtolocalxmlfile.xml"
district_id <- x %>%
read_xml() %>%
xml_find_all('//District') %>%
xml_attrs() %>%
data.frame()这就给了我区号和
Nodes <- x %>%
read_xml() %>%
xml_find_all('//District') %>%
xml_text() 给我区域节点下的每个子节点的文本,但作为折叠字符串。任何关于如何有效地将数据转换为数据帧的想法。
提前感谢!
发布于 2020-07-12 07:37:56
首先,您以标记Zone开始,但以Zones ->结束,并将结束标记修改为Zone。然后阅读并实现以下代码:
library(rvest)
pg <- read_xml("pathtolocalxmlfile.xml")
district_id <- pg %>% xml_find_all("//District") %>% xml_attr("id")
code <- pg %>% xml_find_all("//District/code") %>% xml_text(trim = TRUE)
name <- pg %>% xml_find_all("//District/Name") %>% xml_text(trim = TRUE)
zone_id <- pg %>% xml_find_all("//District/Zone") %>% xml_attr("id")
E1 <- pg %>% xml_find_all("//District/Zone/E1") %>% xml_text(trim = TRUE)
df <- data.frame(district_id, code, name, zone_id, E1)输出:
> df
district_id code name zone_id E1
1 8 1A LALD1 21254 OU29
2 8.1 1B LALD1A 213 OU54
3 8.2 1C LALD1C 214 OU65https://stackoverflow.com/questions/62826772
复制相似问题