【发布时间】:2013-11-17 21:27:32
【问题描述】:
我有the following XML tree 并且只需要为contrib 标签与ref-type"corresp" 的子xref 节点取出名字和姓氏。
<pmc-articleset>
<article>
<front>
<article-meta>
<contrib-group>
<contrib contrib-type="author">
<name>
<surname>Wereszczynski</surname>
<given-names>Jeff</given-names>
</name>
<xref rid="aff1" ref-type="aff"/>
</contrib>
<contrib contrib-type="author">
<name>
<surname>Andricioaei</surname>
<given-names>Ioan</given-names>
</name>
<xref rid="aff1" ref-type="aff"/>
<xref ref-type="corresp" rid="cor1">*</xref>
</contrib>
</contrib-group>
</article-meta>
</front>
</article>
</pmc-articleset>
我看到“Getting the siblings of a node with Nokogiri”指出了可以在 Nokogiri 中使用的 CSS 同级选择器,但是,按照给出的示例,我的代码不加选择地给出了同级。
require "Net/http"
require "nokogiri"
url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?id=PMC1637560&db=pmc"
xml_data = Net::HTTP.get_response(URI.parse(url)).body
parsedoc = Nokogiri::XML.parse(xml_data)
corrdetails = parsedoc.at('contrib:has(xref[text()="*"])')
puts surname = corrdetails.xpath( "//surname" ).text
puts givennames = corrdetails.xpath("//given-names").text
=> WereszczynskiAndricioaei
=> JeffIoan
我只想要 <xref ref-type="corresp">*</> 条件下的兄弟节点,即输出:
=> Andricioaei
=> Ioan
我目前没有参考ref-type 而是选择xref 标记中的星号(两者都合适)。
【问题讨论】:
-
我对 Nokogiri 一无所知,但相关的 XPath 可能是
//name[following-sibling::xref[@ref-type="corresp"]]/concat(given-names, " ", surname)。 -
是 xpath 1.0 吗? nokogiri 不能使用 2.0,我不知道那些选择器在 1.0 中,如果我错了会很棒...
-
我不认为 XPath 1.0 不支持该表达式中的任何内容。
following-sibling::和concat都在规范中。 -
我收到一个错误,提示
)现在有多余的,我不知道如何 -puts corrdetails.xpath("//name[following-sibling::xref[@ref-type="corresp"]]") -
想必你需要在查询中转义
"。顺便说一句,您的 XML 无效。你有</article>,但没有<article>。这可能是复制粘贴错误。
标签: ruby xml xpath css-selectors nokogiri