如何从xml文件创建R语言数据框dataframe

原文链接:http://tecdat.cn/?p=16788

问题重现

软件:R语言

环境:windows

问题描述:我有一个XML文档文件。文件的一部分如下所示:


<?xml version="1.0" encoding="UTF-8"?><List><SubCategory><ID>BO</ID><Name>Bookcases</Name></SubCategory><SubCategory><ID>CH</ID><Name>Chairs</Name></SubCategory><SubCategory><ID>LA</ID><Name>Labels</Name></SubCategory><SubCategory><ID>TA</ID><Name>Tables</Name></SubCategory><SubCategory><ID>ST</ID><Name>Storage</Name></SubCategory><SubCategory><ID>FU</ID><Name>Furnishings</Name></SubCategory><SubCategory><ID>AR</ID><Name>Art</Name></SubCategory><SubCategory><ID>PH</ID><Name>Phones</Name></SubCategory><SubCategory><ID>BI</ID><Name>Binders</Name></SubCategory><SubCategory><ID>AP</ID><Name>Appliances</Name></SubCategory><SubCategory><ID>PA</ID><Name>Paper</Name></SubCategory><SubCategory><ID>AC</ID><Name>Accessories</Name></SubCategory><SubCategory><ID>EN</ID><Name>Envelopes</Name></SubCategory><SubCategory><ID>FA</ID><Name>Fasteners</Name></SubCategory><SubCategory><ID>SU</ID><Name>Supplies</Name></SubCategory><SubCategory><ID>MA</ID><Name>Machines</Name></SubCategory><SubCategory><ID>CO</ID><Name>Copiers</Name></SubCategory></List>

从这个XML文件中,我想创建一个具有ID,name 列的R数据框。请注意,name和ID应包含变量的所有级别。

解决方案

假设这是正确的taxlots.shp.xml文件:


<?xml version="1.0" encoding="UTF-8"?><List><SubCategory><ID>BO</ID><Name>Bookcases</Name></SubCategory><SubCategory><ID>CH</ID><Name>Chairs</Name></SubCategory><SubCategory><ID>LA</ID><Name>Labels</Name></SubCategory><SubCategory><ID>TA</ID><Name>Tables</Name></SubCategory><SubCategory><ID>ST</ID><Name>Storage</Name></SubCategory><SubCategory><ID>FU</ID><Name>Furnishings</Name></SubCategory><SubCategory><ID>AR</ID><Name>Art</Name></SubCategory><SubCategory><ID>PH</ID><Name>Phones</Name></SubCategory><SubCategory><ID>BI</ID><Name>Binders</Name></SubCategory><SubCategory><ID>AP</ID><Name>Appliances</Name></SubCategory><SubCategory><ID>PA</ID><Name>Paper</Name></SubCategory><SubCategory><ID>AC</ID><Name>Accessories</Name></SubCategory><SubCategory><ID>EN</ID><Name>Envelopes</Name></SubCategory><SubCategory><ID>FA</ID><Name>Fasteners</Name></SubCategory><SubCategory><ID>SU</ID><Name>Supplies</Name></SubCategory><SubCategory><ID>MA</ID><Name>Machines</Name></SubCategory><SubCategory><ID>CO</ID><Name>Copiers</Name></SubCategory></List>

XML格式的数据很少以允许该xmlToDataFrame功能正常工作的方式进行组织。最好提取列表中的所有内容,然后将列表绑定到数据框中:


data <- xmlParse("ProductSubcategory.xml")

xml_data <- xmlToList(data)

dataDictionary <- xmlToDataFrame(getNodeSet(data,"//SubCategory"))
(0)

相关推荐