Re: [問題] 新手XML批次轉CSV問題

作者: celestialgod (天)   2016-11-09 21:24:12
※ 引述《qq9966pp (神雞大人)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R做某件事,但是我不知道要怎麼用R寫出來
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 各位先進好,我想用R批次把XML檔轉成CSV檔
: 但是不知道該怎麼做
: 懇求各位幫忙 感謝先
我抓W3school的XML當示範,自己改成自己要的吧
library(plyr)
library(xml2)
library(data.table) # 1.9.7 其他版本沒有fwrite
library(pipeR)
sink('file1.xml')
cat('<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer\'s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with
XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
</catalog>')
sink()
sink('file2.xml')
cat('<?xml version="1.0"?>
<catalog>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon\'s Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon\'s Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
</catalog>')
sink()
list.files(pattern = "\\.xml") %>>%
llply(function(xmlFile){
read_xml(xmlFile) %>>% xml_children %>>% llply(function(node){
tmp <- xml_children(node)
xml_text(tmp) %>>% `names<-`(xml_name(tmp)) %>>% c(xml_attrs(node))
}) %>>% do.call(what = rbind) %>>% data.table
}) %>>% rbindlist %>>% fwrite("output.csv")
不過我保證出來的csv有問題XD,因為xml資料裡面滿滿的逗號
這只是一個範例自行參考(攤手
作者: qq9966pp (神雞大人)   2016-11-10 13:55:00
謝謝大大~我試試看

Links booklink

Contact Us: admin [ a t ] ucptt.com