尝试使用Nokogiri和Ruby解析XML

时间:2010-07-01 17:06:31

标签: ruby rubygems nokogiri

我是编程新手所以请耐心等待。我有一个XML文档,如下所示:

文件名:PRIDE1542.xml

<ExperimentCollection version="2.1">
<Experiment>
    <ExperimentAccession>1015</ExperimentAccession>
    <Title>**Protein complexes in Saccharomyces cerevisiae (GPM06600002310)**</Title>
    <ShortLabel>GPM06600002310</ShortLabel>
    <Protocol>
        <ProtocolName>**None**</ProtocolName>
    </Protocol>
    <mzData version="1.05" accessionNumber="1015">
        <cvLookup cvLabel="RESID" fullName="RESID Database of Protein Modifications" version="0.0" address="http://www.ebi.ac.uk/RESID/" />
        <cvLookup cvLabel="UNIMOD" fullName="UNIMOD Protein Modifications for Mass Spectrometry" version="0.0" address="http://www.unimod.org/" />
        <description>
            <admin>
                <sampleName>**GPM06600002310**</sampleName>
                <sampleDescription comment="Ho, Y., et al., Systematic identification of protein complexes in Saccharomyces cerevisiae by mass spectrometry. Nature. 2002 Jan 10;415(6868):180-3.">
                    <cvParam cvLabel="NEWT" accession="4932" name="Saccharomyces cerevisiae (Baker's yeast)" value="Saccharomyces cerevisiae" />
                </sampleDescription>
                            </admin>
        </description>
        <spectrumList count="0" />
          </mzData>
    </Experiment>
</ExperimentCollection>

我想在<Title><ProtocolName><SampleName>之间删除文本并将其放入文本文件中(我尝试将其加粗以便于查看)。到目前为止,我有以下代码(基于我在本网站上看到的帖子),但它似乎无法工作:

>> require 'rubygems'
>> require 'nokogiri'
>> doc = Nokogiri::XML(File.open("PRIDE_Exp_Complete_Ac_10094.xml"))
>> @ExperimentCollection = doc.css("ExperimentCollection Title").map {|node| node.children.text }

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

尝试使用xpath表达式访问它们。您可以使用斜杠在分析树中输入路径。

puts doc.xpath( "/ExperimentCollection/Experiment/Title" ).text
puts doc.xpath( "/ExperimentCollection/Experiment/Protocol/ProtocolName" ).text
puts doc.xpath( "/ExperimentCollection/Experiment/mzData/description/admin/sampleName" ).text