R の data.frame に処理したい XML ファイル (TEI でエンコードされたプレイ) があります。ここで、data.frame のすべての行には、プレイの 1 行、行番号、その行のスピーカーが含まれています。シーン番号、シーンタイプ。XML ファイルの本文は次のようになります (ただし、より長くなります)。
<text>
<body>
<div1 type="scene" n="1">
<sp who="fau">
<l n="30">Settle thy studies, Faustus, and begin</l>
<l n="31">To sound the depth of that thou wilt profess;</l>
<l n="32">Having commenced, be a divine in show,</l>
</sp>
<sp who="eang">
<l n="105">Go forward, Faustus, in that famous art,</l>
</sp>
</div1>
<div1 type="scene" n="2">
<sp who="sch1">
<l n="NA">I wonder what's become of Faustus, that was wont to make our schools ring with sic probo.</l>
</sp>
<sp who="sch2">
<l n="NA">That shall we know, for see here comes his boy.</l>
</sp>
<sp who="sch1">
<l n="NA">How now sirrah, where's thy master?</l>
</sp>
<sp who="wag">
<l n="NA">God in heaven knows.</l>
</sp>
</div1>
</body>
</text>
この問題は、こことここで提起された質問に似ているように見えますが、私の XML ファイルの構造が少し異なるため、どちらも有効な解決策を提供していません。私はこれを行うことができました:
library(XML)
doc <- xmlTreeParse("data/faustus_sample.xml", useInternalNodes=TRUE)
bodyToDF <- function(x){
scenenum <- xmlGetAttr(x, "n")
scenetype <- xmlGetAttr(x, "type")
attributes <- sapply(xmlChildren(x, omitNodeTypes = "XMLInternalTextNode"), xmlAttrs)
linecontent <- sapply(xmlChildren(x), xmlValue)
data.frame(scenenum = scenenum, scenetype = scenetype, attributes = attributes, linecontent = linecontent, stringsAsFactors = FALSE)
}
res <- xpathApply(doc, '//div1', bodyToDF)
temp.df <- do.call(rbind, res)
これにより、「シーン番号」、「シーン タイプ」、および「スピーカー」がそのままの状態で data.frame が返されますが、それを各行に分割する (および関連する行番号を取得する) 方法がわかりません。
(xmlToList を使用して) ファイルをリストとしてインポートしようとしましたが、リストのリストが非常に乱雑になり、for ループを使用してさまざまな要素にアクセスしようとすると、さまざまなエラーが発生しました (ひどいアイデア、私は知っています!)。
理想的には、ファイル全体がごちゃごちゃしていても機能し、同様に構造化された他の XML ファイルでも機能するソリューションを探しています。
Rを使い始めたばかりで、完全に途方に暮れています。あなたが提供できる支援は、非常に高く評価されます。
ご協力いただきありがとうございます!
編集: 完全な xml ファイルのコピーは、こちらから入手できます。