在R中编辑XML文件
发布时间:2020-12-16 23:06:24 所属栏目:百科 来源:网络整理
导读:我有一个带有以下元素的xml文档: sequence id = "ancestralSequence" taxon id="test" /taxon ACAGTTGACACCCTT/sequence 并且想在“taxon”标签内解析一个新的字符序列.我开始研究XML包文档,但还找不到简单的解决方案.我的代码: # load packagesrequire("X
我有一个带有以下元素的xml文档:
<sequence id = "ancestralSequence"> <taxon id="test"> </taxon> ACAGTTGACACCCTT </sequence> 并且想在“taxon”标签内解析一个新的字符序列.我开始研究XML包文档,但还找不到简单的解决方案.我的代码: # load packages require("XML") # create a new sequence newSeq <- "TGTCAATGGAACCTG" # read the xml secondPartXml <- xmlTreeParse("generateSequences_secondPart.xml") 解决方法
我用xmlParse读取它然后用XPath表达式得到我想要的位.例如,在您的测试数据中,以下是如何获取序列标记中文本的值:
x=xmlParse("test.xml") xmlValue(xpathApply(x,"//sequence")[[1]]) ## [1] "n n ACAGTTGACACCCTTn" – 两个空行,一些空格,然后是基地. 要获取taxon标记中的文本: 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对象中的数据的引用,指针. 无论如何,那应该是你.请注意,“解析”并不意味着完全取代,而是关于我们如何分析表达式中的语法,在这种情况下,选择XML文档的标记,属性和内容. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |