首页 > 解决方案 > 解析从 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="{&quot;Tech&quot;:&quot;Metalic&quot;,&quot;Area&quot;:&quot;&quot;}" />
   <Component Quantity="1.639" PartNumber="Z24206" Designation="" Specification="DN-400" Attributes="{&quot;Tech&quot;:&quot;Composite&quot;,&quot;Area&quot;:&quot;&quot;}" />
 </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 文件,那么它可以正常工作。

标签: rxmlxml-parsing

解决方案


我使用以下方法解决了它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()

这个答案很有帮助。


推荐阅读