gpt4 book ai didi

ruby - 如何根据特定定义的兄弟内容获取 sibling 的 child

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:50 25 4
gpt4 key购买 nike

我需要找到从以下 XML 数据中收集作者和艺术家信息的最佳方法。 comic节点出现多次并包含一本漫画书的数据。

我无法根据他们的工作职能,作家,艺术家等来抓到合适的人。有时每本漫画书都有多个作家和艺术家。我的计划是将每个添加/附加到一个列表。

因此,对于这本漫画书,我需要获取所有作家和艺术家的显示名称,但工作职能(例如作家)是人名的兄弟。

这是我有的,但不起作用:

writer = []
penciler = []
doc.xpath('//comic').each do |main_element|
main_element.xpath("mainsection/credits/credit/role[@id='dfWriter']").each do |n|
writer << n.xpath('person/displayname').text
end
main_element.xpath("mainsection/credits/credit/role[@id='dfPenciler']").each do |n|
penciler << n.xpath('person/displayname').text
end
end

p "Writer(s): ",writer
p "Penciler(s): ",penciler

这是 XML 文件/数据:

<comic>
<id>3398</id>
<index>195</index>
<mainsection>
<title>Mind Games</title>
<myrating>0</myrating>
<myrating>
<displayname>0</displayname>
<sortname>0</sortname>
</myrating>
<pagecount>32</pagecount>
<credits>
<credit>
<role id="dfWriter">Writer</role>
<roleid>dfWriter</roleid>
<person>
<displayname>Will Pfeifer</displayname>
<sortname>Pfeifer, Will</sortname>
<lastname>Pfeifer</lastname>
<firstname>Will</firstname>
</person>
</credit>
<credit>
<role id="dfWriter">Writer</role>
<roleid>dfWriter</roleid>
<person>
<displayname>John Byrne</displayname>
<sortname>Byrne, John</sortname>
<lastname>Byrne</lastname>
<firstname>John</firstname>
</person>
</credit>
<credit>
<role id="dfPenciler">Penciller</role>
<roleid>dfPenciler</roleid>
<person>
<displayname>John Byrne</displayname>
<sortname>Byrne, John</sortname>
<lastname>Byrne</lastname>
<firstname>John</firstname>
</person>
</credit>
</credits>
</mainsection>
</comic>

我的代码没有给我想要的结果。我找到了“Getting the siblings of a node with Nokogiri”,但我需要迭代并捕获每个 sibling 。

我可以通过 <roleid>dfWriter</roleid> 搜索或 <role id="dfWriter">Writer</role>因为它们是一样的。

我的预期输出是:

Writer(s): Will Pfeifer, John Byrne 
Penciler(s): John Byrne

最佳答案

您可以使用 XPath following-sibling为此目的轴假设目标元素总是位于之后 role :

doc.xpath('//comic').each do |main_element|
main_element.xpath("mainsection/credits/credit/role[@id='dfWriter']").each do |n|
writer << n.xpath('following-sibling::person/displayname').text
end
main_element.xpath("mainsection/credits/credit/role[@id='dfPenciler']").each do |n|
penciler << n.xpath('following-sibling::person/displayname').text
end
end

或者您可以首先遍历 credit 而不是 role :

doc.xpath('//comic').each do |main_element|
main_element.xpath("mainsection/credits/credit[role/@id='dfWriter']").each do |n|
writer << n.xpath('person/displayname').text
end
main_element.xpath("mainsection/credits/credit[role/@id='dfPenciler']").each do |n|
penciler << n.xpath('person/displayname').text
end
end

关于ruby - 如何根据特定定义的兄弟内容获取 sibling 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com