我用 xmlParse 读取它,然后用 XPath 表达式得到我想要的部分。例如,对于您的测试数据,以下是如何获取序列标记中文本的值:
x=xmlParse("test.xml")
xmlValue(xpathApply(x,"//sequence")[[1]])
## [1] "\n \n ACAGTTGACACCCTT\n"
-- 两个空行,一些空格,然后是碱基。
要获取分类单元标签中的文本:
xmlValue(xpathApply(x,"//sequence/taxon")[[1]])
## [1] "\n "
——空,只是一个空行。
现在,要将一个字符串替换为另一个字符串,您只需找到“文本节点”,它是一些带有隐形魔法的 XML,因此它看起来就像文本,但实际上并非如此,并将其值设置为某个值。
给定一些包含几个序列的数据,假设您想将每个序列括起来,开头为 CCCCC,结尾为 GGGGGGG:
<data>
<sequence id = "ancestralSequence">
<taxon id="test">Taxon
</taxon>
ACAGTTGACACCCTT
</sequence>
<sequence id = "someotherSequence">
<taxon id="thing">Taxoff
</taxon>
GGCGGCGCGGGGGGG
</sequence>
</data>
代码如下:
# read in to a tree:
x = xmlParse("test.xml")
# this returns a *list* of text nodes under sequence
# and NOT the text nodes under taxon
nodeSet = xpathApply(x,"//sequence/text()")
# now we loop over the list returned, and get and modify the node value:
sapply(nodeSet,function(G){
text = paste("CCCCC",xmlValue(G),"GGGGGGG",sep="")
text = gsub("[^A-Z]","",text)
xmlValue(G) = text
})
请注意,这是完成的引用这在 R 中很奇怪。毕竟,对象x
已经改变了,尽管我们没有直接对其做任何事情。我们在循环中使用的节点是对存储在x
object.
无论如何,这应该对你有用。请注意,“解析”根本不意味着替换,而是关于我们如何分析表达式中的语法,在本例中挑选出 XML 文档的标签、属性和内容。