r - 解析从 R 中的 SQL 查询中检索为文本的 XML
问题描述
我在数据框中以文本形式解析 xml 时遇到问题。
代表:
xml_content <-
'<Content>
<Components>
<Component Quantity="3.891" PartNumber="ABS500" Designation="" Specification="AIMS05-01005" Attributes="{}" />
<Component Quantity="1.109" PartNumber="ABS538" Designation="" Specification="AIMS05-12006" Attributes="{"Tech":"Metalic","Area":""}" />
<Component Quantity="1.639" PartNumber="Z24206" Designation="" Specification="DN-400" Attributes="{"Tech":"Composite","Area":""}" />
</Components>
<Sharepoints>
<Sharepoint DocumentId="11936" IdVersion="1536" Index="6">
<BelongsTo>
<BelongsToComponent ComponentGUID="f7d3c67d-55fe-411c-973a-cce844337f24" ComponentType="Formula" />
</BelongsTo>
</Sharepoint>
<Sharepoint DocumentId="13195" IdVersion="1024" Index="B">
<BelongsTo>
<BelongsToComponent ComponentGUID="c455d81c-32f5-4e8a-815a-c32fde9efad9" ComponentType="Formula" />
</BelongsTo>
</Sharepoint>
</Sharepoints>
</Content>'
df <- data.frame(
part = c("A", "B"),
name = c("Name of A", "Name of B"),
content = c(xml_content, xml_content)
)
这个函数从xmlconvert
返回一个错误:
library(xmlconvert)
xml_to_df(xml_content, records.tag = "Component", fields = "attributes")
xml_to_df(df$content, records.tag = "Component", fields = "attributes")
xml_to_df(df$content, records.tag = "Component", fields = "attributes") 中的错误:文件或 URL ...
此flatxml
功能仅适用于文件:
library(flatxml)
fxml_importXMLFlat()
这个XML
函数也返回一个错误:
library(XML)
xmlTreeParse(df$content)
文档末尾有额外内容错误:1:文档末尾有额外内容
任何人都知道如何从数据框中执行此操作?如果我将文本保存xml_content
为本地 .xml 文件,那么它可以正常工作。
解决方案
我使用以下方法解决了它xml2
:
library(xml2)
data <- read_xml(df$content[1])
Component <- data %>% xml_find_all("//Component")
Quantity <- Component %>% xml_attr("Quantity") %>% as.numeric() %>% as.list()
PartNumber <- Component %>% xml_attr("PartNumber") %>% as.list()
Designation <- Component %>% xml_attr("Designation") %>% as.list()
Specification <- Component %>% xml_attr("Specification") %>% as.list()
这个答案很有帮助。
推荐阅读
- c# - 如何按多个条件对字符串列表进行排序
- javascript - 对象中的 vue.js 循环选项值
- angular - 在 pipe() 中使用 catchError() 会在 .subscribe 变量处显示错误
- java - 在Java中将字符串转换为布尔值的最佳方法
- c - 通过一个项目多次包含相同的源文件是否正确?
- androidx - androidx.spinner onItemSelectedListener 不工作
- spring-boot - Spring Boot 应用程序给出异常 java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/bind/Bindable"
- vb.net - System.IO.Directory.Delete v Git Repository - 未经授权的访问
- python - 从会话 python 请求中删除特定的 cookie
- gnu-make - 混合 GitLab CI 和 make - 如何?