R中的xml-tei:选择节点中的属性

时间:2017-03-13 12:13:19

标签: r xml nodes tei

我有一个xml-tei文件:

#in R
doc  <- xmlTreeParse("FILE_NAME" , useInternalNodes=TRUE, encoding="UTF-8")
ns  =  c(ns =  "http://www.tei-c.org/ns/1.0")
namespaces = ns
getNodeSet(doc,"//* and //@*", ns) 
doc

我正在查看我的xml-tei 中的两个元素<l><w>,以及<l>@xml:id的属性(1) }和(2)<w> type="verb"ana="#confrontation #action #ANT"

#example of element <l> and its child <w> in XML-TEI FILE    
<l n="5b-6a" xml:id="ktu1.3_ii_5b-6a">
 <w>[...]</w>
 <w type="verb" ana="#MḪṢ01 #confrontation #action #ANT" xml:id="ktu1-3_ii_l5b-6a_tmtḫṣ" lemmaRef="uga/verb.xml#mḫṣ">tmtḫṣ</w>
 <g>.</g>
</l>

我使用函数getNodeSet

#in R
l_cont <- getNodeSet(doc, "//ns:l[(@xml:id)]", ns) 
l_cont

当然它会显示<l>中的所有元素和属性。但 我想只选择相关的属性及其值,得到类似的东西:

#in R
xml:id="ktu1.3_ii_5b-6a"
type="verb" ana="#confrontation #action #ANT"

根据另一篇文章Load XML to Dataframe in R with parent node attributes的建议,我做了:

#in R
attrTest <- function(x) {
 attrTest01 <- xmlGetAttr(x, "xml:id")
 w <- xpathApply(x, 'w', function(w) {
  ana <- xmlGetAttr(w, "ana")
  if(is.null(w))
 data.frame(attrTest01, ana)
 })
do.call(rbind, w)
}
res <- xpathApply(doc, "//ns:l[(@xml:id)]", ns ,attrTest)
temp.df <- do.call(rbind, res)

但它不起作用......我得到了错误:

> res <- xpathApply(doc, "//ns:l[(@xml:id)]", ns ,attrTest)
Error in get(as.character(FUN), mode = "function", envir = envir) : 
objet 'http://www.tei-c.org/ns/1.0' de mode 'function' introuvable
> temp.df <- do.call(rbind, res)
Error in do.call(rbind, res) : objet 'res' introuvable

你有什么建议吗? 提前谢谢

1 个答案:

答案 0 :(得分:1)

我建议使用 R 包 tei2r。 (https://rdrr.io/github/michaelgavin/tei2r/) 在处理 TEI 编码文件时,这个包对我有帮助。

从这个包中,我将使用函数 importTexts 导入文档和 parseTEI 函数来获取您正在寻找的确切节点。

另一种导入和提取的方法可能是:

Conditions